var name = 'The Window';
var object = {
name: 'My Object',
getNameFunc: function(){
return function() {
return this.name;
};
}
};
console.log( object.getNameFunc()() );
when i tested the code. the result is The Window. but i think this.name; should be My Object. what’s wrong with my thinking.
when i add var before the name : "My Object", it show’s an error.? why?
thisinside a function is the “receiver” it was invoked upon.That is,
for the construct
x.f(),thisinside the function (f) will evaluate to the value ofx.for all other cases,
thiswill evaluate towindowinside the invoked function. (The functionscall,apply, andbindcan also alterthis… but that’s another story.)In the posted example the second function (the one with
this.name) is not invoked using thex.f()form and sothisis thewindowobject.The “simple fix” is to use a closure: (The first function is invoked in the
x.f()form and thusthisis the same asobject, which is as expected. We capture the value ofthisin the current scope via a closure created withselfand the returned function.)However, I may consider another design, depending 🙂
Happy coding.
Additional clarification, for comment:
…that is because you are using
circle.getArea()which is of the formx.f(). Thusthisinside the getArea function evaluates tocircle.In the code posted you are invoking two different functions in a row. Imagine writing the code like this:
The first function call is in the form of
x.f()and thusthisinside getNameFunc is the evaluation ofobject. However, in the second line, the function (nameFunc) is not invoked in the formx.f(). Therefore, thethisinside nameFunc (the function returned from getNameFunc) will evaluate towindow, as discussed above.