我在这里复制了来自 MDN 的代码片段:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind
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 中总是绑定(bind)到全局对象。我知道可以有 var self 或 var that 在 bloom 函数中。
该行中有两个 this
,但是 this
指的是什么以及它是如何工作的,这完全令人困惑。
如何运作?
最佳答案
首先阅读这个 article ,它很好地解释了 this
的工作原理。
.bind(this, args)
只是帮助您将 this
上下文传递到您的函数中(因为在您的示例中默认情况下在它里面 this
是 undefined
或引用 window
)。
bind
也是一个很好的替代方法:
// Declare bloom after a delay of 1 second
LateBloomer.prototype.bloom = function() {
var self = this;
window.setTimeout(self.declare, 1000);
};
作为 es6
中的最后一点,您可以通过这种方式完成:
window.setTimeout(() => {
//do some stuff
}, 1000);
代替
window.setTimeout(function () {
//do some stuff
}.bind(this), 1000);
这让你不用去想this
。
关于javascript - 设置超时,绑定(bind)和这个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38736902/