Skip to content Skip to sidebar Skip to footer

"object Is Not A Function" When Saving Function.call To A Variable

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 somethin

Solution 1:

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)

Solution 2:

Try this:

functiontest(){
   var a = function(args){
       returnArray.prototype.slice.call(args);
   };
   b = a(arguments);
   // Do somethingsetTimeout(function(){
     var c = a(arguments);
     // Do something else
   }, 200);
}

The same error will happen if you try doing something like:

var log = console.log;
log("Hello");

The reason is that when you do this you are assigning the function x (in my example log) to the variable log. BUT the function contains a call to this which now refers to window and not to console, which then throws an error that this is not an object

Solution 3:

The problem is that call is a method (a function that belongs to an object) that expects its owner (its this) to be a function. When you write a = Array.prototype.slice.call, you're copying the function, but not the owner.

The "object is not a function" message isn't saying that a isn't a function, it's saying that its this isn't a function. You could technically achieve what you describe by writing a.call(Array.prototype.slice, arguments), but obviously that's not what you want!

Post a Comment for ""object Is Not A Function" When Saving Function.call To A Variable"