setInterval函数可以't读取数组
setInterval function can't read array
可能重复:
通过正确的“这";要设置超时回调的上下文?
我的小剧本有问题。
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和/或更早版本。
相关文章:
- 如何在Immutable.js中读取数组中的值
- 如何在不赋值数组变量的情况下读取数组数据
- 角度无法读取数组中的对象
- setInterval函数可以't读取数组
- 动态读取数组值形成 JSON 对象
- AngularJS读取数组长度
- 如何从 html 读取数组到 js
- 无法读取数组
- 使用 getElementById 动态读取数组
- 我怎么能读取数组我保存在一个cookie与jquery.cookie
- 如何从另一个文件读取数组数据
- Javascript console.log未读取数组未定义
- 如何在jQuery中读取数组的每个元素
- 在Javascript中使用数组读取数组
- Javascript无法读取数组键
- 如何使用JavaScript在Json中读取数组
- 使用JavaScript或jQuery读取数组JSON
- 在游戏循环中未正确读取数组值
- 使用 JavaScript 读取数组 JSON
- 在JavaScript中读取数组的' length '属性是否真的是一个昂贵的操作