我在JavaScript中遇到this
和setInterval
的问题。我在这里阅读了几个解决方案,但无法让它们为我工作。这是我的代码:
var timer_func = function(){
var that = this;
var inspect = function(clusters){
var clength = "";
for(var i = 0; i < that.clusters.length; i++){ //---> undefined that.clusters.length
clength += that.clusters[i].processes.length + ",";
}
console.log(clength);
}
var inspector = setInterval(inspect, 1000);
};
//much later
timer_func();
我是100%我在调用this.clusters
之前在我的代码中初始化了这里所谓的timer_func()
,但显然我尝试访问的变量是未定义的(而如果我将其打印在其他地方以外的地方)超时不是)。有什么建议吗?感谢。
答案 0 :(得分:1)
我说问题在于你如何拨打timer_func()
,而不是使用setInterval()
。如果您希望 this
内的timer_func()
引用您通过this
外部设置属性的同一对象{{1然后按如下方式调用它:
timer_func()
答案 1 :(得分:1)
永远不会在对象上定义属性clusters
,也不会将参数clusters
传递给内部函数。您可以进入两个方向之一,指定属性或传递参数。
var timer_func = function(){
this.clusters = ["cluster1", "cluster2"];
var that = this;
var inspect = function(clusters){
var clength = "";
for(var i = 0; i < that.clusters.length; i++){ //---> undefined that.clusters.length
clength += that.clusters[i].processes.length + ",";
}
console.log(clength);
}
var inspector = setInterval(inspect, 1000);
};
//much later
timer_func();
var timer_func = function(){
var that = this;
var inspect = function(clusters){
var clength = "";
for(var i = 0; i < clusters.length; i++){
clength += clusters[i].processes.length + ",";
}
console.log(clength);
}
var inspector = setInterval(function(){
var clusters = ["cluster1", "cluster2"];
inspect(clusters)
}, 1000);
};
//much later
timer_func();