嘿,我一直在试图了解bind()方法在JS中的作用,并且我发现了SO,MDN和git中的一些有用的资源,这些资源解释得非常好,但我是仍然与我在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
指向?
'this'都指向同一个东西,当你调用这个函数的时候,这个对象在点之前。 – elclanrs
@elclanrs窗口?我教的绑定被用来避免指向窗口! –
Bothe指的是'bloom'被调用的同一个对象实例 –