简体   繁体   English

Javascript - 在一个运行间隔的函数内调用时不能使用对象方法?

[英]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.

相关问题 当在对象内部调用函数时,JavaScript会监听 - JavaScript listen for when a function is called inside an object 当调用 object 时,在 object 中自动运行 function - Automatically running a function inside an object when that object is called Javascript function 内部 Object 方法:您何时应该(并且不应该)在 ZC1C4252674C1788 中包含返回? 下面的示例代码 - Javascript function inside Object Methods: When should you (and shouldn't) include return inside a function? Sample code below Javascript无法在函数内调用对象 - Javascript can't call an object inside a function 可以调用 javascript Function 对象吗? - Can a javascript Function object be called? Javascript Function实例会自动转换为对象,因此无法再调用 - Javascript Function instance is automatically casted to object and can't be called anymore 创建js对象时,为什么不能在另一个已定义函数中使用已定义函数? - Why can't I use a defined function inside another defined function,when creating an js object? 调用javascript函数时无法读取$ _POST数据 - Can't read $_POST data when a javascript function is called Javascript 在 class 方法中使用匿名 function - Javascript use anonymous function inside class methods JavaScript-加载页面后无法调用计时器函数 - JavaScript - can't make the timer function to be called when the page is loaded
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM