Skip to content Skip to sidebar Skip to footer

A Shorthand For Function.prototype.call.call?

Ways to call a function Consider this simple function: function my(p) { console.log(p) } I can call it like this: my('Hello'); And also like so: my.call(this, 'Hello'); Moreover

Solution 1:

When you say

var call = Function.prototype.call.call;

the last call loses its actual context. You need to explicitly say that the call belongs to Function.prototype.call.

You can do that, by creating a new function, which actually binds it like this

var call = Function.prototype.call.call.bind(Function.prototype.call);
call(my, this, "Hello");
// Hello

The bind function returns a new function, which when invoked will have the context (this) set as Function.prototype.call.

Solution 2:

call, presumably, makes use of this internally.

By calling it without context, you've changed the internal value of this from something that has access to the function prototype to window.

Solution 3:

If you want to do that, then consider this (if you have an ES5 compliant interpreter):

var call = Function.prototype.call.bind(Function.prototype.call)

The bind function makes sure that the context (the this variable) while making the function call is Function.prototype.call instead of undefined, as you see in your case.

Post a Comment for "A Shorthand For Function.prototype.call.call?"