-1

我在 JavaScriptthis中遇到了问题。setInterval我在这里阅读了一些关于 SO 的解决方案,但无法让它们为我工作。这是我的代码:

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(),但显然我尝试访​​问的变量是未定义的(而如果我在超时之外的其他地方打印它不是)。有什么建议吗?谢谢。

4

2 回答 2

1

我想说问题在于你如何调用timer_func(),而不是使用setInterval(). 如果您想this 在内部 timer_func()引用您通过this 外部 timer_func()设置属性的同一对象,请按如下方式调用它:

timer_func.call(this);
于 2013-02-12T10:13:34.350 回答
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();

于 2013-02-12T10:21:26.280 回答