In the code below, there are two functions, the outer function, and the inner IIFE function.
The output for the code below is:
outer func: this.foo = bar
outer func: self.foo = bar
inner func: this.foo = undefined
inner func: self.foo = bar
I do not understand why in the inner IIFE function, this
cannot be used to access the foo variable while self
still can. I understand that var self
is a global varible for the inner function and can still be accessed. But what about this
?
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);
}());
}
};
myObject.func();