嘿,伙计们,我一直在努力学习bind()方法在JS中的作用,我在所以、MDN和git中找到了一些有用的资源,它们确实很好地解释了这一点,但是我仍然有点困惑于我在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()一样,这是我目前所理解的,但它所做的是,它可以延迟函数的执行,同时保留或者更确切地说,将this的值绑定到特定的函数。
现在在下面的代码行中:
LateBloomer.prototype.bloom = function() {
window.setTimeout(this.declare.bind(this), 1000);
}; 第一个this指向什么?那么分段this指向什么呢?
发布于 2015-04-25 11:54:54
在this.declare.bind(this)中,第一个this用于获取当前对象的declare方法。然后,我们使用bind创建一个新函数,该函数将使用特定的this值调用该方法,这是bind()的参数。只是碰巧我们将它绑定到当前对象,所以我们在这两个地方都使用了this,但我们不必这么做。我们可以写:
var another = new LateBloomer;
setTimeout(this.declare.bind(another), 1000);这将获取当前对象的declare方法,并安排在1秒内在another上调用它。
https://stackoverflow.com/questions/29864734
复制相似问题