這是關於解決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