I tried the following in the Google Chrome console:
> function t1(f) { return f(1); }
> function t2() { return this+1; }
> t1(t2.call)
TypeError: object is not a function
Why does this not work? Is there a way to define a function in lieu of Function.prototype.call that would work here?
It doesn’t work because when you’re passing
t2.call, you’re actually just passing.call. In other words, it doesn’t remember the object from which it was passed.To accomplish what you wanted, you can use
.bind().This binds the
t2function as thethisvalue of.call, which means you’ll be calling.callas though you had done this:…which is what you wanted.
The
.bindmethod is not supported in IE8 and lower, as well as some other older browsers, but you can implement a mostly complete shim in those cases.FYI, if you need this a lot, you could bind
.callas the calling context of.bindto shorten it a bit.So now you have a
.bind()function with.call()bound as its calling context. When you invoke it, it will be as if you were doing this:So
callBind()will return a function withthe functionbound as the calling context of.call, just like we did above. So you’d use it like this: