这是关于解决this
价值。这是通过以下方式解决:
myObject.something();//this in something is myObject
window.something();//this is window
button.onClick=function();//this when button is clicked is button
如何解决它已经给出,它使用的setTimeout
var test = function() {
var me = this;// set reference to this
this.sayAgain=function(){
console.log("Hi, I am "+me.toString());
}
}
test.prototype.toString=function(){
return "test";
}
test.prototype.say = function() {
console.log("Hi, I am "+this.toString());
}
var t = new test();
setTimeout(t.say,50);//=window passing functon without ref to this
setTimeout(function(){
t.say();
},150);//=test passing ref with function
setTimeout(t.sayAgain,200);//=test using me as the saved this context
第二种超时传递一个closure在下面的例子中传递回调像一个常见的错误setTimeout,如果你打算通过说回调数百次,但只创建了几个测试对象实例,那么最后一个(sayAgain)的执行会稍微好一些。
这是因为您在创建测试实例时创建闭包,但在传递sayAgain作为回调时不会创建封闭,如果创建了很多测试实例并且不会多次传递say
,那么请将this.me和this.sayAgain从功能体并通过say
作为封闭。
您可以使用Function.prototype.bind,但它不支持在IE < 8中,我不确定它是否会像我的示例中使用t.say
那样创建闭包。
来源
2013-07-08 01:38:00
HMR