In a global scope, this === window
.
So, this
is a simple accessor to window
(like a pointer in C
or a reference in PHP
).
In the facts, assigments likes var x = 'toto'
can be fetched with:
console.log(window.x);
console.log(x);
console.log(this.x);
Example:
var x = 'toto'; // assignment before mythis definition
var mythis = (function(self) { // mythis definition
return self;
})(this);
var y = 'tata'; // assignment after mythis definition
console.log(mythis.x); // display toto
console.log(this.x); // display toto
console.log(window.x); // display toto
console.log(mythis.y); // display tata
console.log(this.y); // display tata
console.log(window.y); // display tata
Live example:
Codepen