When to use self in JavaScript

后端 未结 3 1050
夕颜
夕颜 2020-12-08 02:49

I\'ve noticed that calls like setTimeout() work either as :

self.keyword()

or just on their own e.g. keyword().

3条回答
  •  旧巷少年郎
    2020-12-08 03:06

    self can refer to the window object, but typically that's not the case here. You'll see this commonly above that setTimeout():

    var self = this;
    

    They're keeping a reference to the current object, so later when you call self.keyword() you're calling that method on that object, not any other.

    Say you have for example images in the page you wanted to rotate every 2 seconds...you'd want each of those 3 timers to refer to their own methods. If they use this directly, it would (most of the time) refer to window and not the current object, whereas passing another variable in maintains the current reference.

提交回复
热议问题