I'm a fresh hand in Javascript. Now I'm trying to understand Closure. In most common case it's easy to understand. But there are still something very confusing. This might be a question about this
in javascript. I'm not sure about it.
Here are 3 examples: 1:
var name = "The Window";
var object = {
name: "My Object",
getNameFunc: function() {
return this.name;
}
};
console.log(object.getNameFunc()); // 'My Object'
2:
var name = "The Window";
var object = {
name: "My Object",
getNameFunc: function() {
return function() {
return this.name;
};
}
};
console.log(object.getNameFunc()()); // 'The Window'
and last one:
var name = "The Window";
var object = {
name: "My Object",
getNameFunc: function() {
var that = this;
return function() {
return that.name;
};
}
};
console.log(object.getNameFunc()()); // 'My Object'
First one is very easy to understand. But why second one return The Window
and third one return My Object
.