Javascript 另一个设定区间&;这不管用
我对JavaScript中的Javascript 另一个设定区间&;这不管用,javascript,Javascript,我对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++){ //---&g
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();
var timer\u func=function(){
var=这个;
var检查=功能(群集){
var clength=“”;
对于(var i=0;i未定义that.clusters.length
clength+=that.clusters[i].processs.length+“,”;
}
控制台日志(长度);
}
var检查器=设置间隔(检查,1000);
};
//很久以后
定时器函数();
我100%初始化了这里所说的
this。在调用timer\u func()
之前,在我的代码中聚集,但显然我试图访问的变量未定义(而如果我在超时之外的其他地方打印它,则不会)。有什么建议吗?谢谢。我想说问题在于如何调用timer\u func()
,而不是使用setInterval()
。如果希望this
内部timer\u func()
引用通过this
外部timer\u func()
设置属性的同一对象,请按如下方式调用它:
timer_func.call(this);
属性clusters
从未在对象上定义,参数clusters
也没有传递给内部函数。可以从两个方向中选择一个,指定特性或传递参数
指定属性
var timer\u func=function(){
this.clusters=[“cluster1”、“cluster2”];
var=这个;
var检查=功能(群集){
var clength=“”;
对于(var i=0;i未定义that.clusters.length
clength+=that.clusters[i].processs.length+“,”;
}
控制台日志(长度);
}
var检查器=设置间隔(检查,1000);
};
//很久以后
定时器函数();
传递参数
var timer\u func=function(){
var=这个;
var检查=功能(群集){
var clength=“”;
对于(var i=0;i
您是否看到timer\u func
具有任何集群
属性?您的inspect()
函数中的集群
参数是什么?当您通过setInterval()
实际调用inspect()
时,不会传入任何参数,但在任何情况下,您实际上都不会在函数中的任何位置使用该参数。我非常关注setInterval,所以没有想到这一点。非常感谢,这就是问题所在。我完全混淆了timer\u func
的范围和包含我的timer\u func
函数的对象的范围。谢谢你的深入回答。@Masiar很高兴我能帮上忙。所以我猜第二种方法是你需要的?是的。但你的回答让我明白了原因。
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();