标签:style class blog code java http
在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();
}3 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();
}
参考文章
js面向对象编程:this到底代表什么?,布布扣,bubuko.com
标签:style class blog code java http
原文地址:http://blog.csdn.net/xuexiaodong009/article/details/29800247