In global scope, is there a difference between
this.myvar = 42;
and
var myvar = 42;
?
(In strict-mode, if that matters.)
And if so, what is the difference, esp. when referencing myvar in functions?
(The question might be related to this.)
In global scope, is there a difference between
this.myvar = 42;
and
var myvar = 42;
?
(In strict-mode, if that matters.)
And if so, what is the difference, esp. when referencing myvar in functions?
(The question might be related to this.)
No There is no difference. in global scope. but if you go inside a function and say 'this' it still refers to window. that's why normally when go deep into function developers normally equalize var self = this; before go to function and use self.variableName;
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);
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