javascript - 用对象调用setTimeOut的函数,结果意外?

标签 javascript

我正在尝试解决 JS 难题,但是我不确定为什么在 setTimeOut 函数中使用 ralph.bark 不起作用(不记录 Ralph..)?

我们正在针对范围内的特定对象调用 bark 函数(而不是 this.bark ,后者会使“this”指向窗口..),因此“this”应该设置为 ralph Should'是吗?有人可以解释为什么这不起作用吗?

var Dog = function( name ) {
    this.name = name;
}

Dog.prototype.bark = function() {
    console.log( this.name );
}

// make a new instance of a Dog
var ralph = new Dog('Ralph');

// make Ralph bark once immediately
ralph.bark();


// in 2 second we want Ralph to bark again
// this works

setTimeout(ralph.bark.bind(ralph), 2000);

// this does not work, WHY?
// setTimeout(ralph.bark, 2000);

最佳答案

setTimeout(ralph.bark, 2000) 不会调用 ralph.bark。它只是将函数的引用传递给setTimeoutsetTimeout 然后在延迟后执行该函数。当它发生时,它将类似于 callback();,因此函数内的 this 将引用 window

这个的工作原理在 MDN documentation 中有详细解释。 .

<小时/>

也许这会让事情变得更清楚:

function bark() {
    console.log( this.name );
}

var Dog = function( name ) {
    this.name = name;
}

Dog.prototype.bark = bark;

现在,无论您执行 setTimeout(ralph.bark, 2000); 还是 setTimeout(bark, 2000); 都没有什么区别,因为 ralph.barkbark 引用同一个函数。

函数是一流的对象。它们不属于或绑定(bind)到任何东西,除非您明确这样做 (.bind(ralph))。

另请参阅:How to access the correct `this` / context inside a callback?

关于javascript - 用对象调用setTimeOut的函数,结果意外?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23050112/

相关文章:

javascript - ( Node :1572) UnhandledPromiseRejectionWarning: ValidationError: profile validation failed: education. 0.fieldsofstudy:需要路径 `fieldsofstudy`

javascript - ES6 - 有条件地在 Promise 中发出重试信号,直到达到最大重试次数

JavaScript 内部函数 & 'this'

javascript - jquery 复选框,如何获取所有选中的复选框并将它们添加到数组?

javascript - 如何在 JavaScript\HTML 中使用套接字?

javascript - Vue JS 组件间数据可用性

javascript - 我如何组合两个数组以使用react以获得一个包含前两个数组中所有项目的新数组?

javascript - 从javascript添加从数组中动态选择的选项

javascript - 访问路由端点之外的 req 属性

javascript - Angularjs 和 yeoman 的当前位置