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
?
self refers to the global scope - If the context is a window it will refer to window.self, while in case of a non-windowed context it will refer to the global scope of that context (e.g. in service worker code, self refers to the worker global scope).
self refers to the global scope of a context:
https://developer.mozilla.org/en-US/docs/Web/API/Window/self
Other replies have pointed out that
self
is not going to refer to theFORM
and thatself
iswindow
. They're right;self
iswindow
. Well, except when it isn't. In either IE6 or IE7 (forgot),self.onload
would not fire, thoughwindow.onload
would.All official versions of IE (and even IE9pr3) have an odd, intransitive implementation of
==
with these host objects. Using==
to compare eitherwindow
orself
to a node in the document, the result istrue
.IE Oddities
Never, unless I wanted to create a
self
variable in the scope of a function referring to the context for later reference,You should use
this
to refer to the element at hand, notself
. In global scope thoughthis
is a reference towindow
, andself
is alsowindow
.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 thefoo
objectdoLater
was originally called on, a var namedself
is used. It could be anything but 'self' has meaningful semantics.