Regarding this code:
var name = "Jaguar";
var car = {
name:"Ferrari",
getName:function(){
return this.name;
}
};
alert((car.getName = car.getName)());
The output is: Jaguar.
Why does this object correspond to Window and not the object contained in the car variable?
It seems that the fact to reassign the object’s function to itself leads to lose the assignment of this to the object when the function is called…
I’m trying to guess: Does it exist a kind of mechanism (using variable or other) that keep an eye on the non-reassignement of an object’s function so that if that situation happens, this mechanism would prevent the assignement of the this keyword as usual (as being equals to the object)?
The reason is fairly subtle:
thisin JavaScript is determined entirely by how a function is called. To havethisset tocarduring the call togetName, you have to callgetNameimmediately upon retrieving it from thecarobject, like this:(Or via
Function#callorFunction#apply, which let you specify the value forthisexplicitly.)What you’re doing in your example is effectively this:
…which is different. Functions called in that way get
thisset to the global object (window, in browsers). (Except in strict mode; in strict modethiswould beundefined.)More (from my anemic blog):
thisI’m not entirely sure I follow that question, but if you want to have a function that always has a preset
thisvalue, then yes, there are a couple of ways to do that.One is to use the new ES5 function
bind:bindreturns a function that always hasthisset to the argument you give it.The other way is to use a closure. And in fact, you can create a
bind-like function in ES3 very easily:That doesn’t do everything
binddoes, but it does thethispart. Then you’d have:More on closures (again from the blog):
In a future spec, we’ll be getting a declarative way of creating functions that have a preset
thisvalue (so-called “arrow functions” because the syntax for them involves uses=>rather than thefunctionkeyword).