Transcript for .prototype.call.call function?
Function call methods
Consider this simple function:
function my(p) { console.log(p) }
I can call it like this:
my("Hello");
And also like this:
my.call(this, "Hello");
It is also possible:
Function.prototype.call.call(my, this, "Hello");
Reducing the functional way
I am interested in the last option - the most functional, but since it has been trying to make a shortcut for too long:
var call = Function.prototype.call.call;
to call me like this:
call(my, this, "Hello");
But I am getting this TypeError:
TypeError: Function.prototype.call called on incompatible undefined
Does anyone know what is wrong here?
source to share
When you speak
var call = Function.prototype.call.call;
the latter call
loses its actual context. You need to explicitly say what call
belongs Function.prototype.call
.
You can do this by creating a new function that actually binds it like this
var call = Function.prototype.call.call.bind(Function.prototype.call);
call(my, this, "Hello");
// Hello
The function bind
returns a new function that, when called, will have the context ( this
) specified as Function.prototype.call
.
source to share
If you want to do this, consider this (if you have an ES5 compatible interpreter):
var call = Function.prototype.call.bind(Function.prototype.call)
The bind function makes sure that the context (variable this
) when calling the function Function.prototype.call
instead of undefined
as you see in your case.
source to share