1

im new to javascript and would like to know what will be the output of the code:

var myObject = {
    foo: "bar",
    func: function() {
    var self = this;
    console.log("outer func:  this.foo = " + this.foo);
    console.log("outer func:  self.foo = " + self.foo);
    (function() {
        console.log("inner func:  this.foo = " + this.foo);
        console.log("inner func:  self.foo = " + self.foo);
    }());
    }
};

Not sure how foo works yet.

Arnold Cristobal
  • 743
  • 2
  • 11
  • 30
  • 5
    Maybe you could try this by yourself? You don't need a community to try that code, you can do it by yourself. – Cary Bondoc Aug 18 '15 at 05:31

1 Answers1

5

Every function call in Javascript resets the value of this based on how the function was called (see this answer for the five ways that this is controlled).

So, when you use the IIFE structure (function() { ... })() which is just a normal function call, the value of this is reset to either the window object or to undefined if running in strict mode.

So, if you are not running in strict mode, then the this.foo reference in the inner func will be attempting to access window.foo which will probably be undefined.

And, sure enough when I run this in a jsFiddle that is not in strict mode, and actually call myObject.func() the console shows:

outer func:  this.foo = bar
outer func:  self.foo = bar
inner func:  this.foo = undefined
inner func:  self.foo = bar

An additional console.log() statement confirms that in the inner func this === window and, of course, window.foo is undefined.


If you run your code in strict mode, then calling myObject.func() will generate this error Uncaught TypeError: Cannot read property 'foo' of undefined because in the inner func, this === undefined.

Community
  • 1
  • 1
jfriend00
  • 580,699
  • 78
  • 809
  • 825