Is it important for the anonymous function/closure to retain the scope of the object where it originated?
var person = {
name: "John",
func: function() {
var self = this;
console.log("outer function: this.name = " + this.name);
console.log("outer function: self.name = " + self.name);
(function() {
console.log("inner function: this.name = " + this.name);
console.log("inner function: self.name = " + self.name);
}());
}
};
person.func();
Both examples yield the same result.
var person = {
name: "John",
func: function() {
var self = this;
console.log("outer function: this.name = " + this.name);
console.log("outer function: self.name = " + self.name);
return function() {
console.log("inner function: this.name = " + this.name);
console.log("inner function: self.name = " + self.name);
};
}
};
person.func()();
// output
outer function: this.name = John
outer function: self.name = John
inner function: this.name = undefined
inner function: self.name = John