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, this is possible:
Function.prototype.call.call(my, this, "Hello");
A shorthand for the functional way
I am interested in the last option - the most functional one, but since it's too long I tried to make a shorthand:
var call = Function.prototype.call.call;
in order to call my like this:
call(my, this, "Hello");
But I get this TypeError:
TypeError: Function.prototype.call called on inpatible undefined
Anybody knows, what's wrong here?
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, this is possible:
Function.prototype.call.call(my, this, "Hello");
A shorthand for the functional way
I am interested in the last option - the most functional one, but since it's too long I tried to make a shorthand:
var call = Function.prototype.call.call;
in order to call my like this:
call(my, this, "Hello");
But I get this TypeError:
TypeError: Function.prototype.call called on inpatible undefined
Anybody knows, what's wrong here?
Share Improve this question edited Jun 17, 2015 at 10:49 thefourtheye 240k53 gold badges465 silver badges500 bronze badges asked Jun 17, 2015 at 10:47 Anton HaraldAnton Harald 5,9745 gold badges31 silver badges68 bronze badges3 Answers
Reset to default 8When 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
.
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
.
If you want to do that, then consider this (if you have an ES5 pliant 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.