Ben Nelson Ben Nelson - 1 year ago 102
Javascript Question

Difference between this and self in JavaScript

Everyone is aware of

in javascript, but there are also instances of
encountered in the wild, such as here

So, what is the difference between
in JavaScript?

Answer Source

Unless set elsewhere, the value of self is window because JavaScript lets you access any property x of window as simply x, instead of window.x. Therefore, self is really window.self, which is different to this.

window.self === window; // true

If you're using a function that is executed in the global scope, this is set to window, and therefore

function foo() {
        window.self === window, // is self window?
        window.self === this,   // is self this?
        this === window         // is this window?
foo(); // true true true

If you're using a function in a different context, this will refer to that context, but self will still be window.

// invoke foo with context {}{}); // true false false

You can find window.self defined in the W3C 2006 working draft for the Window Object here.

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