If there is no binding of functions to instances in javascript how does getName() return john
function Person() {
this.name = "john";
this.getName = function() {
return this.name;
};
}
var me = new Person();
setTimeout(function(){alert(me.getName())}, 3000);
I though this would refer to the window at the point of call from setTimeout.
See jsFiddle: http://jsfiddle.net/qZeXG/
What’s happening here is that the anonymous function executed by
setTimeoutcloses over themevariable, which is aPersoninstance. Because of closure, you can still referencemewhen that function is later called.When you invoke
me.getName()you’re invoking a method on thePersoninstance, which sets the value ofthistomeinside that function. This is just a normal method invocation.Note that in the following code:
…the value of
thisin the firstalertis thewindowobject. It’s the ordinary method invocation that is changing the value.Consider this final example:
In this case the function also closes over a reference to
getName, but the function that that variable points to is invoked without any information about thePersoninstance it came from. Therefore, the value ofthisinsidegetNamewill be thewindowobject.Conclusion? This statement:
…is a false assumption.