In Javascript, every single function call causes a new value of this
to be set and if it is just a plain function call, then this
is set to either the global object (which is window
in a browser) or undefined
(if running in strict mode). That's what is happening for you. In this line:
object.getNameFunc()()
object.getNameFunc()
makes the first method call and returns the internal anonymous function. Then, the last ()
is just a regular function call of that function and that regular function call causes this
to get set to the global object (window
in your case). Any plain function call resets the value of this
to window
or undefined
. This is how Javascript works.
Here's a simple demo that show you how this
is reset:
See this answer for the five ways that the value of this
is controlled.
You can work around this issue in several ways by either saving the value of this
in the parent function or using one of the methods to explicitly control the value of this
.
One of the simpler mechanisms to understand is to just save the value you want in the parent function:
var myName = "The Window";
var object = {
myName: "My Object",
getNameFunc: function () {
var self = this;
return function () {
return self.myName;
};
}
};
document.write(object.getNameFunc()()); // "My Object"
Or, you can use .bind()
:
var myName = "The Window";
var object = {
myName: "My Object",
getNameFunc: function () {
return function () {
return this.myName;
}.bind(this);
}
};
document.write(object.getNameFunc()()); // "My Object"
FYI, I changed your variable name to myName
so there could never be any confusion in following what was happening with window.name
which already exists in the browser environment.