javascript函数小知识

  javascript中的函数跟其他语言的函数有很大的不同,让人觉得怪怪的。尤其是有无括号、有无new,结果大不同,this指向也有莫测的变化。
<script type="text/javascript">
	//关于函数小知识,wallimn
	function func(){  
	    this.id='func';  
	}  
	  
	var a = func;//把func对应的函数赋值给a,此函数并没有被执行。此后,a()相当于func(),也就是说a、func指向相同的函数体。  
	console.log(a)//输出为函数定义  
	console.log(a.id);//输出为undefined
	console.log(window.id);//输出为undefined,因为只进行了函数赋值操作,函数没有执行  
	var b = func();//把func函数的执行结果赋值给b,func函数没有返回值,那么b为undefined。此过程中func体中的this指window。根据window.id的输出可知  
	console.log(b)//输出为undefined  
	//console.log(b.id)//执行会出错。
	console.log(window.id);//输出为func,函数普通调用(不用new)时,内部的this指向window  
	var c = new func();//相当于把func当作一个构造函数执行,返回一个对象赋值给c。此时是可以调用c.id。函数体中的this指向函数执行后形成的上下文  
	console.log(c);//输出为创建的对象,this指针指向函数执行上下文。  
	console.log(c.id);//出为func  
	var d = new func();  
	d.id="new func";  
	console.log(c.id);//输出为func  
	console.log(d.id);//输出为new func。每次new,得到独立的上下文。  
</script>

猜你喜欢

转载自wallimn.iteye.com/blog/2372580