setInterval函数可以't读取数组

setInterval function can't read array

本文关键字:读取 数组 函数 setInterval      更新时间:2023-09-26

可能重复:
通过正确的“这";要设置超时回调的上下文?

我的小剧本有问题。

function test() {
    this.arr = new Array('a','b','c');
    this.func = function() {
        //Do something with this.arr. But it's undefined.. WHY???
    }
    this.Start = function() {
        this.Interval = setInterval(this.func, 1000);
    }
}
var Test = new test();
Test.Start();

当我试图用"func"中的数组做任何事情时,它总是告诉我,数组是未定义的。为什么?

您得到了错误的this引用,请尝试:

function Test() {
  this.arr = new Array('a','b','c');
  this.func = function() {
    console.log(this.arr);
  };
  this.start = function() {
    var fun = this.func.bind(this);
    this.interval = setInterval(fun, 1000);
  };
}
var test = new Test();
test.start();

如果您需要更多信息,这篇关于this的文章非常有趣:函数调用和这个

另外,请注意,我已经更改了一些符号的大小写。记住,用作构造函数的函数以大写字母开头,变量和方法使用小写字母。

在全局作用域上调用计时器/间隔,因此"this"设置为"window"。为了解决这个问题,您可以将第三个选项传递给setInterval(),该选项将用作指定函数调用的参数。

function Test(){
    this.array = new Array('a','b','c');
    this.function = funct(){ }
    this.start = function(){
        this.Interval = setInterval(function(passedObj){
            passedObj.funct.call(passedObj);
        },1000,this);
    }
}
var testObj = new Test();
testObj.start();

阅读下面的评论,你会发现这是针对nodejs的。然而,这将不适用于IE8和/或更早版本。