如何在setInterval和setTimeout函数中更改"this"的范围

Joh*_*ohn 2 javascript object settimeout setinterval

怎么可以在this里面使用setIntervalsetTimeout调用?

我想用它像:

function myObj() {
  this.func = function(args) {
    setTimeout(function() { 
      this.func(args);
    }, 1000);
  }
}
Run Code Online (Sandbox Code Playgroud)

前段时间我用.onclick这种方式做了事:

this.click = function(func) {
  this.elem.onclick = (function(func, obj) {return function(){func.apply(obj)} })(func,this);
};
Run Code Online (Sandbox Code Playgroud)

但我不知道我能为做intervalstimeouts.

Jar*_*Par 9

最简单的方法就是保存this到本地.本地self不受具体的上下文改变setIntervalsetTimeout回调调用.它将保持原始this

function myObj() {
  var self = this;
  this.func = function(args) {
    setTimeout(function() { 
      self.func(args);
    }, 1000);
  }
}
Run Code Online (Sandbox Code Playgroud)