What does "self" mean in javascript?

Nick Van Brunt picture Nick Van Brunt · Jul 9, 2010 · Viewed 23.9k times · Source

I read here that "self Refers to the current window or form".

Self does not seem to refer to the current form in this case:

<form><input type="text" onkeyup="alert(self.foo.value)" name="foo"></form>

However in this case it works (referring to the window):

<form><input type="text" onkeyup="alert(self.document.forms[0].foo.value)" name="foo"></form>

So when would you use the self DOM property over just window?

Answer

Garrett picture Garrett · Jul 10, 2010

Other replies have pointed out that self is not going to refer to the FORM and that self is window. They're right; self is window. Well, except when it isn't. In either IE6 or IE7 (forgot), self.onload would not fire, though window.onload would.

All official versions of IE (and even IE9pr3) have an odd, intransitive implementation of == with these host objects. Using == to compare either window or self to a node in the document, the result is true.

IE Oddities

alert(self == document.body); // true
alert(document.body == self); // false
alert(window == self); // true
alert(window === self); //false
var b = document.createElement("b");
alert(window == b); // false
alert(window == document.body.appendChild(b)); // true
alert(window == document.body.removeChild(b)); // false