I have the following code snippet.
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();
with the following results.
outer func: this.foo = bar
outer func: self.foo = bar
inner func: this.foo = undefined
inner func: self.foo = bar
I have a few questions about this code snippet.
- What is the idea of putting the nested function inside the outer function. How would that benefit real life code?
- I'm also struggling with the 'this' keyword, I always thought 'this' represented the global context, so I'm confused with how it works in the outer function but not in the inner function.