在這裏,我複製的代碼片段從MDN:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind的setTimeout,結合這
function LateBloomer() {
this.petalCount = Math.ceil(Math.random() * 12) + 1;
}
// Declare bloom after a delay of 1 second
LateBloomer.prototype.bloom = function() {
window.setTimeout(this.declare.bind(this), 1000);
};
LateBloomer.prototype.declare = function() {
console.log('I am a beautiful flower with ' +
this.petalCount + ' petals!');
};
var flower = new LateBloomer();
flower.bloom();
// after 1 second, triggers the 'declare' method
最令人困惑的部分是:window.setTimeout(this.declare.bind(this), 1000);
我瞭解this
工程和this
裏面的setTimeout總是勢必對全球對象。我知道可以有var self或var裏面bloom功能。
該行有兩個this
,但其中this
指的是什麼以及如何工作是完全混淆。
工作原理?
這兩個'這'是同一個對象。 'Bind'返回帶有上下文或明確設置的this的函數。所以當'setTimeout'最終運行時,它不能覆蓋'this'到全局,所以它仍然被設置爲'bloom'方法的'this'。 – ste2425