When to use self in JavaScript

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.

Leave a Comment

deneme bonusu veren sitelerbahis casino