Difference between this and self in JavaScript
Difference between this and self in JavaScript
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 youre using a function that is executed in the global scope and is not in strict mode, this
defaults to window
, and therefore
function foo() {
console.log(
window.self === window, // is self window?
window.self === this, // is self this?
this === window // is this window?
);
}
foo(); // true true true
If youre using a function in a different context, this
will refer to that context, but self
will still be window
.
// invoke foo with context {}
foo.call({}); // true false false
You can find window.self
defined in the W3C 2006 working draft for the Window Object here.
A slight addition to this as people may encounter this in the context of service workers, in which case it means something slightly different.
You might see this in a service worker module:
self.addEventListener(install, function(e) {
console.log([ServiceWorker] Install);
});
Here self refers to the WorkerGlobalScope, and this is the standard method for setting event listeners.
From Mozilla docs:
By using self, you can refer to the global scope in a way that will work not only in a window context (self will resolve to window.self) but also in a worker context (self will then resolve to WorkerGlobalScope.self).
Difference between this and self in JavaScript
Although I am late here but I came across one example which too can be helpful to understand this
further:
var myObject = {
foo: bar,
func: function() {
var self = this;
console.log(outer func: this.foo = + this.foo);
console.log(outer func: self.foo = + self.foo);
(function() {
console.log(inner func: this.foo = + this.foo);
console.log(inner func: self.foo = + self.foo);
}());
}
};
myObject.func();
O/P
outer func: this.foo = bar
outer func: self.foo = bar
inner func: this.foo = undefined
inner func: self.foo = bar
Prior to ECMA 5,
this
in the inner function would refer to the global window object; whereas, as of ECMA 5,this
in the inner function would be undefined.