Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"object is not a function" when saving function.call to a variable

Tags:

javascript

I was trying to make my code smaller by caching functions to variables. For example:

function test(){
   var a = Array.prototype.slice,
   b = a.call(arguments);
   // Do something
   setTimeout(function(){
     var c = a.call(arguments);
     // Do something else
   }, 200);
}

So instead of calling Array.prototype.slice.call(arguments), I can just do a.call(arguments);.

I was trying to make this even smaller by caching Array.prototype.slice.call, but that wasn't working.

function test(){
   var a = Array.prototype.slice.call,
   b = a(arguments);
   // Do something
   setTimeout(function(){
     var c = a(arguments);
     // Do something else
   }, 200);
}

This gives me TypeError: object is not a function. Why is that?

typeof Array.prototype.slice.call returns "function", like expected.

Why can't I save .call to a variable (and then call it)?

like image 493
Rocket Hazmat Avatar asked Dec 16 '11 16:12

Rocket Hazmat


1 Answers

Function.prototype.call is an ordinary function that operates on the function passed as this.

When you call call from a variable, this becomes window, which is not a function.
You need to write call.call(slice, someArray, arg1, arg2)

like image 52
SLaks Avatar answered Nov 09 '22 21:11

SLaks