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?

+3


source to share


3 answers


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

.

+8


source


call

is presumably used this

internally.



By calling it without context, you changed the internal value this

to whatever has access to the function prototype, to window

.

+4


source


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.

+3


source







All Articles