理解MDN的绑定示例

时间:2015-04-25 11:47:48

标签: javascript

嘿伙计们,我一直在努力学习JS中的bind()方法,我在SOMDNgit中找到了一些有用的资源。这个相当不错,但我仍然对我在MDN上找到的实际例子感到困惑。 我正在谈论以下代码:

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!');
};  

现在绑定函数就像call()或apply(),这就是我到目前为止所理解的,但它的作用是,它可以延迟函数的执行,同时保留或更确切地绑定{{1}的值到一个特定的功能。

现在在下面的代码行中:

this

第一个LateBloomer.prototype.bloom = function() { window.setTimeout(this.declare.bind(this), 1000); }; 指向的是什么?而this指向的是什么?

1 个答案:

答案 0 :(得分:2)

this.declare.bind(this)中,第一个this用于获取当前对象的declare方法。然后我们使用bind创建一个新函数,该函数将使用特定this值调用该方法,并且该参数是bind()的参数。碰巧我们将它绑定到当前对象,因此我们在这两个地方使用this,但我们不必这样做。我们可以写:

var another = new LateBloomer;
setTimeout(this.declare.bind(another), 1000);

这会获取当前对象的declare方法,并安排在1秒后在another上调用它。