Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "self" mean in javascript?

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?

like image 207
Nick Van Brunt Avatar asked Jul 09 '10 20:07

Nick Van Brunt


People also ask

What is self and top in JavaScript?

In the Window object, top references the topmost window. While self references the current window.

Is self the same as this in JavaScript?

So, within the inner function, "this" refers to the object calling the inner function while "self" refers to the object which called the outer function to create the reference to the inner function.

Why self is needed instead of this in JavaScript?

var self = this; In the JavaScript, “self” is a pattern to maintaining a reference to the original “this” keyword and also we can say that this is a technique to handle the events.

What is window self?

The Window. self read-only property returns the window itself, as a WindowProxy . It can be used with dot notation on a window object (that is, window. self ) or standalone ( self ).


1 Answers

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 
like image 160
Garrett Avatar answered Sep 24 '22 01:09

Garrett