1

Why does an immediately invoked method return the window object as this,

var o = {};  
o.foo = function () {  
    console.log(this);  
}(); //Window {…}

but when executed later, the method returns the object o (as I would have expected in both cases)?

var o = {};
o.foo = function () {
    console.log(this);
}
o.foo(); //Object {foo: function}
Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
alexafluor
  • 13
  • 3

4 Answers4

5

"this" is defined at the time of invocation. Variable assignment occurs from right to left, so the function is being invoked before any assignment has been made and therefore "this" still refers to the global window object.

adrichman
  • 1,215
  • 10
  • 17
  • 1
    Mostly correct but executing the IIFE creates a new execution context. Because *this* wasn't set in the call, *this* in the new execution context is set to the global object, it doesn't "still" refer to the global object. – RobG Apr 14 '14 at 01:46
  • This and RobG's answer make sense. I didn't know assignments were right associative. Helpful table of [javascript operators and associativity](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table). – alexafluor Apr 14 '14 at 04:07
1
var o = {};  
o.foo = function () {  
    console.log(this);  
}(); //

This is the global context, that is why your're seeing the window object. To get it show your o object you need to bind it to the o object. this refers to the object in current context. the value of this always holds the window object when it is not in any other context.

o.foo = function () {  
    console.log(this);  
}.bind(o); //

Demo: http://jsfiddle.net/X6cyr/1/

Ryan
  • 14,392
  • 8
  • 62
  • 102
  • 2
    Not about context (the value of *this* here is from a function context). The value of *this* is not set in the call, so it defaults to the global object. – RobG Apr 14 '14 at 01:28
  • @RobG So I explained it wrong? – Ryan Apr 14 '14 at 01:33
  • The term "context" is often used inappropriately in conjunction with *this*. The *this* keyword is a parameter of an execution context that is set by how a function is called (or use of *bind*). Its value is totally independent of the execution context in which the call is made. – RobG Apr 14 '14 at 03:03
1

When you execute an immmediately invoked function expression (IIFE):

... = (function () {  
         console.log(this);
      }());

the value of this is not set by the call, so on entering the function it is undefined so is set to the global object. In strict mode, it will remain undefined.

RobG
  • 142,382
  • 31
  • 172
  • 209
0

if you execute console.log(this) in object defination body, defaultly it will refer to Window object, because your object is not existed in browser. so you must execute function after your defination of object, here is my DEMO http://jsfiddle.net/X6cyr/2/

Jesse
  • 517
  • 5
  • 24