setInterval, this, again

前端 未结 5 1520
故里飘歌
故里飘歌 2021-01-27 16:32

I have a problem in regard to setInterval that I can\'t figure out.

There is the problem with the scope when calling setInterval or timeout fro

5条回答
  •  死守一世寂寞
    2021-01-27 17:22

    Hoist _this out of the bing function.

    you should have

    _this = this,
    this.bing = function() {
                intervalID2 = setInterval(function(){
                    console.log(_this.name);
                }, 500)   
    }  
    

    Javascript is imperative so you need to follow the execution path carefully. In function Ship, this points to a Ship object, in function bing, this points to the global scope (window). You need to save a reference to this so that you can refer back to it in these types of functions.

提交回复
热议问题