Konrad Konrad - 1 month ago 5
Javascript Question

When to use self in JavaScript

I've noticed that calls like

setTimeout()
work either as :

self.keyword()


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

What is the different between the two calls?

Answer

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.