[英]Javascript - can't use object methods when called inside a function thats running through interval?
I'm getting undefined function when I try to do the following (simplified for readability) 当我尝试执行以下操作时,我得到了未定义的函数(为了便于阅读而简化)
function object() {
this.bar = function() { };
this.foo = function() {
this.bar();
};
this.z = setInterval(this.foo, 1000);
}
This code gives 'undefined function this.bar()' when executed from within the interval, but not when this.foo is called outside of the interval. 当从区间内执行时,此代码给出'未定义的函数this.bar()',但是当在区间之外调用this.foo时不会。
How can I achieve this? 我怎样才能做到这一点?
That is correct - you can't do it that way. 这是正确的 - 你不能这样做。 The
this
pointer will not be set correctly when called from setInterval()
(it is probably set to point to the global window
object). 从
setInterval()
调用时,不会正确设置this
指针(它可能设置为指向全局window
对象)。 You can change your code like this to solve the problem: 您可以像这样更改代码来解决问题:
function object() {
this.bar = function() { };
this.foo = function() {
this.bar();
};
var self = this; // save reference to local object in variable other than 'this'
this.z = setInterval(function() {
self.foo(); // call method on local object
}, 1000);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.