Why won't this Javascript method keep calling itself?

前端 未结 4 1995
無奈伤痛
無奈伤痛 2021-01-18 14:12

I have a JavaScript object with a privileged method. When this method has completed, I would like it to call itself (after a small timeout) and continue running indefinitely

4条回答
  •  一整个雨季
    2021-01-18 15:04

    Because this outside the function is not the same as this inside the function. Try instead:

    function Test() {
        // ... private variables that testMethod needs to access ...
        var me = this;
        this.testMethod = function() {
            alert("Hello, from the method.");
            setTimeout(me.testMethod, 2000);
        };
    }
    

提交回复
热议问题