js面向对象编程:this到底代表什么?

来源:互联网 发布:wampserver多域名绑定 编辑:程序博客网 时间:2024/05/16 07:42

    在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的总结

 

1 0
原创粉丝点击