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
.