3

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.)

Community
  • 1
  • 1
Albert
  • 65,406
  • 61
  • 242
  • 386

2 Answers2

0

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;

  • I thought, in strict mode, a function in global scope, if I just call it by name, has `this === undefined`. I would have to call it like `this.myFunc()`. – Albert Mar 07 '14 at 09:18
0

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

Paul Rad
  • 4,820
  • 1
  • 22
  • 23