setTimeout() 和 setInterval() 调用的代码或者函数是全局作用域的
要传递this通过匿名函数来实现:
var
show
=
function
(){
alert( this + " is all " );
}
var Obj = function (){
this .show = function (){
alert( this + " is obj " );
}
this .time = function (){
var self = this ;
// setTimeout(function(){this.show();}, 2000);//window is all
setTimeout( function (){self.show();}, 2000 ); // Obj is obj
// setTimeout("this.show()", 2000);//window is all
// setTimeout("self.show()", 2000);//window is all
// setTimeout(this.show, 2000);//window is obj
// setTimeout(self.show, 2000);//window is obj
}
}
var obj = new Obj();
obj.time();
alert( this + " is all " );
}
var Obj = function (){
this .show = function (){
alert( this + " is obj " );
}
this .time = function (){
var self = this ;
// setTimeout(function(){this.show();}, 2000);//window is all
setTimeout( function (){self.show();}, 2000 ); // Obj is obj
// setTimeout("this.show()", 2000);//window is all
// setTimeout("self.show()", 2000);//window is all
// setTimeout(this.show, 2000);//window is obj
// setTimeout(self.show, 2000);//window is obj
}
}
var obj = new Obj();
obj.time();