2015-04-25 206 views
2

嘿,我一直在试图了解bind()方法在JS中的作用,并且我发现了SO,MDNgit中的一些有用的资源,这些资源解释得非常好,但我是仍然与我在MDN上找到的一个实际例子有点混淆。 下面的代码我谈论:了解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!'); 
}; 

现在绑定功能,正如调用()或应用(),我是这么理解的,到目前为止,但它的作用是,它可以延迟功能的执行同时保留this的值或将其绑定到特定功能。

现在在下面的行代码:

LateBloomer.prototype.bloom = function() { 
     window.setTimeout(this.declare.bind(this), 1000); 
    }; 

什么是第一this指向?什么是this指向?

+2

'this'都指向同一个东西,当你调用这个函数的时候,这个对象在点之前。 – elclanrs

+0

@elclanrs窗口?我教的绑定被用来避免指向窗口! –

+0

Bothe指的是'bloom'被调用的同一个对象实例 –

回答

2

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

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

这得到当前对象的declare方法,并安排在1秒调用它another

+0

所以这两种情况都是指LateBloomer的实例? –

+1

是的,没错。我试图用更一般的形式来描述它。 – Barmar