Konrad Konrad - 1 year ago 52
Javascript Question

When to use self in JavaScript

I've noticed that calls like

work either as :


or just on their own e.g.

What is the different between the two calls?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download