In the following code, the first function is not bound to obj, but the second function is, so f() returns fifi and g() returns Mark Twain as expected. But the 3rd attempt, it is by (obj.getCallBack) first, which is now a function, and then it is invoked, essentially it should be the same as the f case. But they do print out Mark Twain instead. Why are they not bound to obj using bind() but still got executed with this pointing to obj?
(the 4th attempt is just a usual invocation of a method, and this should bind to the object on which the method is invoked on).
(tested on the current Chrome, Firefox, and IE 9)
window.name = "fifi";
var obj = {
name: "Mark Twain",
getCallBack: function() {
return this.name;
}
}
var f = obj.getCallBack;
var g = f.bind(obj);
console.log(f);
console.log(f());
console.log(g);
console.log(g());
console.log((obj.getCallBack)());
console.log(obj.getCallBack());
You are forgetting that if a function is called as a property of some object, that object will be the
thisfor the call. So:After these basic rules, the bound function will be invoked, which can be thought of as a proxy function (any shim does this) that uses
.call/.applyto explicitly set the context for the target function. So thethisvalue for the proxy function doesn’t matter, but behind the scenes it was set by the basic rules.Edit:
(obj.getCallBack)does not return the function as value, because getValue is not called.. So it is exactly the same asobj.getCallbackand the first post applies.So you can do this and not get an error:
As opposed to: