setInterval, this, again

前端 未结 5 1476
故里飘歌
故里飘歌 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:30

    By the time setTimeout() gets around to call your method, it only sees the function and not the invocation context (i.e. the object to bind it to); much like this:

    var bing = ships[i].bing;
    
    bing(); // inside bing(), this == window
    

    Basically, you need to provide setTimeout() with a prewired method invocation:

    var bound_bing = ships[i].bing.bind(ships[i]);
    timeoutID2 = setTimeout(bound_bing, 1000);
    

    The "magic" happens with .bind() as it returns a new function that will have this set up properly.

提交回复
热议问题