views:

180

answers:

4

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?

+3  A: 

Never, unless I wanted to create a self variable in the scope of a function referring to the context for later reference,

function Constructor() {
    var self = this;
}

You should use this to refer to the element at hand, not self. In global scope though this is a reference to window, and self is also window.

meder
+2  A: 

For all windows, the self and window properties of a window object are synonyms for the current window, and you can optionally use them to refer to the current window. For example, you can close the current window by calling the close method of either window or self. You can use these properties to make your code more readable or to disambiguate the property reference self.status from a form called status.

Mike
so I guess self == window. The link I posted is very misleading. If that is a quote could you post the source?
Nick
Original source http://docs.sun.com/source/816-6408-10/window.htm. Modern source http://dev.w3.org/html5/spec/Overview.html#dom-self
bobince
+1  A: 

self is not a reserved keyword or standard type, but has become a defacto standard name when for keeping reference to an object for closures.

Here we create a closure to pass to setTimeout(). When that closure is executed, this will refer to the global object. To keep a reference to the foo object doLater was originally called on, a var named self is used. It could be anything but 'self' has meaningful semantics.

Foo.prototype.doLater = function() {
  var self = this; // current object

  window.setTimeout(function() { self.doSomething(); }, 1000);
}

new Foo().doLater();
Chadwick
+1  A: 

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

Garrett