Zack Newsham Zack Newsham - 5 months ago 6
Javascript Question

Why can't the call member of a function be assigned to a variable

I'm working on a transcoder for a project and came across an unusual edge case.

I have the following:

function a(func){
return func.call()
}


for various reasons the transcoder wants to change it to:

function a(func){
var tmp = func.call;
var res = tmp()
return res;
}


However, the call to
tmp()
comes back with
tmp is not a function
. If I debug and pause just by this line,
tmp
is defined as a function.

Does it have something to do with it's signature being
function call(){ [native code]}
?

Are there other functions that will trigger similar errors?

Is there a way around this, other than simply not doing it?

EDIT:
I found another case, it looks like it may be to do with the object's context:

a = { toString: null }.propertyIsEnumerable
a("toString")


throws the same error.

EDIT: some context;
I am writing the transcoder, it has a very specific use case where each line of the code is separated into it's simplest component parts. It's possible that I simply can't separate it further than this. Using the example above, func.call() is a member access operation followed by a call expression, I want to separate out the member access and call expression into two separate expressions.

Answer

If you want to store a method in a variable, instead of doing

 var f = obj.mymethod;
 f();

You can do

 var f = obj.mymethod.bind(obj);
 f();
Comments