JavaScript setInterval 没有正确绑定到正确的闭包

2022-01-24 00:00:00 node.js javascript meteor coffeescript

大家好,我是 JavaScript 的新手,我来自 Python 和 Java 非常面向对象的世界,这是我的免责声明.

Hi people, I'm reasonably new to JavaScript and I come from the very object-oriented world of Python and Java, that's my disclaimer.

下面有两块代码,替代实现,一个在 JavaScript 中,一个在 Coffeescript 中.我正在尝试在 Meteor.js 应用程序的服务器上运行它们.我遇到的问题是当使用绑定方法this.printSomething"作为我的回调调用函数setInterval"时,一旦执行该回调,它就会失去实例的范围,导致this.bar"未定义!谁能向我解释为什么 JavaScript 或 coffescript 代码不起作用?

There are two chunks of code below, alternative implementations, one in JavaScript, one in Coffeescript. I am trying to run them on the server in a Meteor.js application. The problem I am experiencing is when calling the function "setInterval" using the bound-method "this.printSomething" as my callback, once that callback is executed, it loses scope with the instance resulting in "this.bar" being undefined! Can anyone explain to me why either the JavaScript or the coffescript code isn't working?

function Foo(bar) {
  this.bar = bar;

  this.start = function () {
    setInterval(this.printSomething, 3000);
  }

  this.printSomething = function() {
    console.log(this.bar);
  }
}

f = new Foo(5);
f.start();

咖啡脚本实现

class foo
    constructor: (bar) ->
        @bar = bar

    start: () ->
        Meteor.setInterval(@printSomething, 3000)

    printSomething: () ->
        console.log @bar

x = new foo 0
x.start()

推荐答案

您在 setInterval 回调中丢失了 Foo 的上下文.您可以使用 Function.bind 来将上下文设置为类似这样以将回调函数引用的上下文设置回 Foo 实例.

You lose your context of Foo in the setInterval callback. You can use Function.bind to set the context to something like this to set the context for the callback function reference back to Foo instance.

setInterval(this.printSomething.bind(this), 3000);

随叫随到

setInterval(this.printSomething, 3000);

回调方法获取全局上下文(在 web 的情况下为窗口或在节点等租户的情况下为全局),因此您不会从 this 那里获得属性 bar指的是全局上下文.

The callback method gets the global context (window in case of web or global in case of tenants like node) so you don't get property bar there since this refers to the global context.

小提琴

或者只是

 this.printSomething = function() {
     console.log(bar); //you can access bar here since it is not bound to the instance of Foo
  }

相关文章