passing this.method in setTimeout doesn't work?

前端 未结 1 1857
心在旅途
心在旅途 2020-12-12 02:21

I am seeing problem with passing object method as argument to setTimeout. I know inside nested function, scope of this need to be set manually but what if i directly pass fu

相关标签:
1条回答
  • 2020-12-12 03:01

    The MDN documentation of setTimeout has a whole section about it, I recommend to read it.


    Inside the callback you pass to setTimeout, this will refer to window, not to the instance of your class.

    If the function is called, this.count (which refers to window.count) would be undefined, since there is no global count variable. Later it would become NaN (undefined++ is NaN). The count property of your object would not change at all.

    By calling the function explicitly as a method of the object (self.counting()), you ensure that this correctly refers to the instance of your class.

    You could achieve the same by using .bind [MDN], instead of using another function:

    setTimeout(this.counting.bind(this), this.start);
    

    Read this MDN article to learn more about this.

    0 讨论(0)
提交回复
热议问题