javascript - 设置超时,绑定(bind)和这个

标签 javascript this settimeout

我在这里复制了来自 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 selfvar that 在 bloom 函数中。

该行中有两个 this,但是 this 指的是什么以及它是如何工作的,这完全令人困惑。

如何运作?

最佳答案

首先阅读这个 article ,它很好地解释了 this 的工作原理。

.bind(this, args) 只是帮助您将 this 上下文传递到您的函数中(因为在您的示例中默认情况下在它里面 thisundefined 或引用 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/

相关文章:

angularjs $timeout 最大值

JavaScript setTimeout 不起作用

angular - 向返回 promise 的 javascript 方法添加延迟

JavaScript 和 XPath : not loading all matches of tag

javascript - 未嵌入帖子中的禁用按钮

javascript - 使用 TypeScript 自定义 knockout 验证规则

Jquery (this)closest 不起作用?

javascript - React js 中的环绕

javascript - 是否有适用于 Eclipse 的有效 Javascript 自动完成或内容辅助?

c++ - 运算符 != 不匹配(操作数类型为指针和对象)