Why won't this Javascript method keep calling itself?

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

    When you first call it with "myTest.testMethod();" the "this" keyword is bond to your "myTest" object, when the timeout fires the "window" object is bond to "this" keyword and "this.testMethod" is equivalent to "window.testMethod". Try:

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

    Or:

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

提交回复
热议问题