Why won't this Javascript method keep calling itself?

前端 未结 4 2036
無奈伤痛
無奈伤痛 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:14

    because the this in your setTimeout is referring to the local function testMethod not Test -- essentially, you are saying setTimeout( testMethod.testMethod, 2000 )

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

提交回复
热议问题