this is one of most mystery feature in JavaScript, after assigning the object method to other variable, the binding (this keyword) is lost
var john = {
name: 'John',
greet: function(person) {
alert("Hi " + person + ", my name is " + this.name);
}
};
john.greet("Mark"); // Hi Mark, my name is John
var fx = john.greet;
fx("Mark"); // Hi Mark, my name is
my question is:
1) what is happening behind the assignment? var fx = john.greet;
is this copy by value or copy by reference?
fx and john.greet point to two diferent function, right?
2) since fx is a global method, the scope chain contains only global object. what is the value of this property in Variable object?
1)
fxandjohn.greetare referring to the same function object, the assignment operation for objects, works by reference.For primitive values, like
String,Number,Booleanundefinedornull, a copy of the value will be made.2) The
thisvalue refers to the global object.The
thisvalue is not a property of the Variable Object and it has nothing to do with the scope chain, is a special reserved word, and it is determined implicitly when a function is called (you can also set it explicitly viacallorapply).JavaScript internally handles a
Reference type, which consists of two components, the base object and the property name, when a function is invoked, thethisvalue is determined implicitly by getting the base object (by the internalGetValueoperation).And finally, the last case where
thisis set implicitly is when you invoke a function with thenewoperator, thethiskeyword will refer to a newly created object.So in brief, here is how
thisworks implicitly:1- When a function is called as a method (the function is invoked as member of an object):
2- A normal function call:
3- When the
newoperator is used: