js面向对象编程:this究竟代表什么?

    在js中this的使用方法非常让人迷惑。有些像Java或者C#中的this,但又不全然一样。依照流行的说法this总是指向调用方法的对象。

   1、纯粹函数调用。     

 function ListCommon2(x)
	 {
	    this.x=x;	
		alert("this 是 ListCommon2"+(this instanceof ListCommon2));
		alert("this.constructor"+this.constructor);	
	 }        
         function test(){
	                //測试代码
					var t1=ListCommon2("烧水");
				   var t2=new ListCommon2("烧水2");							
	     }
 经过測试发现,

                         假设不使用new,也就是var t1=ListCommon2("烧水");这样调用,this是全局对象Window对象,

                         假设使用new,也就是var t2=new ListCommon2("烧水2");;这样调用,this就变成了new出来的实例对象的应用,也就是 t2,

看来和调用方式也是有关系的。

2、作为方法调用,那么this就是指实例化的对象。

 function ListCommon2(x)
	 {
	    this.x=x;	
	    this.Do=function(x)//特权方法 实例方法
		{
		  alert("this 是 ListCommon2"+(this instanceof ListCommon2));
	    	alert("this.constructor"+this.constructor);
		}
	 } 
      ListCommon2.prototype.Do2=function()//实例方法
	  {
	  
	      alert("this 是 ListCommon2"+(this instanceof ListCommon2));
	    	alert("this.constructor"+this.constructor);
	  }
     	 
         function test(){
	                //測试代码
					var t1=ListCommon2("烧水");
				//	t1.Do();调用错误
				//	t1.Do2();调用错误
				   var t2=new ListCommon2("烧水2");							
				   t2.Do();
				   t2.Do2();
	     }

经过測试发现。无论是特权方法类型的实例方法,还是原型类型的实例方法,this都指向了当前新创建的对象。

apply,call调用

apply的第一个參数就是this。假设没有传递this就是全局对象。

改变this的方法。通过new能够改变,使用call和apply也能够改变

4 setTimeout中的this

 function ListCommon2(x)
	 {
	    this.x=x;	
	    this.Do=function(x)//特权方法 实例方法
		{
		  window.setTimeout(function(){ 
		  alert("this 是 ListCommon2"+(this instanceof ListCommon2));
	    	  alert("this.constructor"+this.constructor);
		 
		 },100); 	
		}
	 } 
      ListCommon2.prototype.Do2=function()//实例方法
	  {
	     window.setTimeout(function(){ 
		  alert("this 是 ListCommon2"+(this instanceof ListCommon2));
	    	  alert("this.constructor"+this.constructor);
		 
		 },100); 	     
	  }
     	 
         function test(){
	                //測试代码				
				   var t2=new ListCommon2("烧水2");							
				   t2.Do();
				   t2.Do2();
	     }

測试发现setTimeout中的this也是全局对象Window对象。当然这种样例还有非常多,感觉应该是实例化的对象,可实际上却不是。因此须要注意。


參考文章

js中this的使用方法

js中this的总结

 

posted @ 2017-04-17 21:39  lytwajue  阅读(373)  评论(0编辑  收藏  举报