JavaScript setInterval not being properly bound to correct closure(JavaScript setInterval 没有正确绑定到正确的闭包)
问题描述
大家好,我是 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
}
这篇关于JavaScript setInterval 没有正确绑定到正确的闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JavaScript setInterval 没有正确绑定到正确的闭包
基础教程推荐
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 动态更新多个选择框 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01