Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this return a reference to the global window object, even though 'this' is within another function

Tags:

javascript

if (typeof obj == 'undefined') {
  obj = {};
}

obj.thing = new function () {
  if (typeof this.global == 'undefined') {
    this.global = (function () {return this;})();
  }
}

this.global is assigned to this inside of a function. So, why does this return a reference to the window object?

console.log(this) > DOMWindow
console.log(obj.thing.global) > DOMWindow
console.log(window) > DOMWindow

I would love to understand this better.

like image 739
Joel Klabo Avatar asked Nov 13 '22 12:11

Joel Klabo


1 Answers

In ES 3 and ES 5 there is a this keyword associated with every execution context (ES 3) or Lexical Environment (ES 5). The value is set according to the rules for entering global or function code as described in ECMA-262 §10.4.

In your code you have:

  this.global = (function () {return this;})();  

Where the result of calling an anonymous function is assigned to this.global. Within that anonymous function, the value of this is set according to the algorithm in §10.4.3.

Since the function is called without setting the value of this, and the code is not in strict mode, the value of this is set to the global object (which, in a browser, is generally the window object) per step 2 of the algorithm.

If the code was in strict mode, then the value of this within the anonymous function would be undefined, which is the value that would be assigned to this.global.

like image 81
RobG Avatar answered Nov 16 '22 02:11

RobG