The reason is pretty subtle: this in JavaScript is completely determined by how the function is called. In order for this set car during a call to getName , you must immediately call getName after retrieving it from the car object, for example:
car.getName() // or car["getName"]()
(Or via Function#call or Function#apply , which allows you to explicitly specify a value for this .)
What you do in your example is really like this:
// Set f to the result of the assignment expression, // which is a reference to the getName function var f = (car.getName = car.getName); // Call it (separately) f();
... that's different. Functions called this way get this for the global object ( window , in browsers). (Other than strict mode, in strict mode this will be undefined .)
More (from my anemic blog):
Is there some kind of mechanism (using a variable or another) that monitors the non-use of the object function, so if such a situation occurs, will this mechanism prevent the assignment of this keyword as usual (as equal to the object)?
I'm not quite sure that I am following this question, but if you want to have a function that always has a predefined value of this , then yes, there are several ways to do this.
One of them is to use the new ES5 bind function:
var name = "Jaguar"; var car = { name: "Ferrari" }; car.getName = function(){ return this.name; }.bind(car); alert((car.getName = car.getName)());
bind returns a function that always has this given by the argument you give it.
Another way is to use closure. And in fact, you can easily create a bind like function in ES3:
function pseudoBind(func, thisArg) { return function() { return func.apply(thisArg, arguments); }; }
This does not all bind , but has a part of this . Then you will have:
var name = "Jaguar"; var car = { name: "Ferrari" }; car.getName = pseudoBind(function(){ return this.name; }, car); alert((car.getName = car.getName)());
More on closing (again from the blog):
In the future specification, we will get a declarative way of creating functions with a predefined value of this (the so-called arrow functions, because the syntax for them includes using => , and not the keyword function ).