Function.prototype.apply not working on Function.prototype.call in Chrome

The title should be self-explanatory and I am wondering if there is a workaround for this.

Window.call.apply;
>> function apply()

Window.call.apply();

>> Uncaught TypeError: Window.call.apply is not a function
    at <anonymous>:2:13
    at Object.InjectedScript._evaluateOn (<anonymous>:895:140)
    at Object.InjectedScript._evaluateAndWrap (<anonymous>:828:34)
    at Object.InjectedScript.evaluate (<anonymous>:694:21)

      

Basically, I'm surprised I'm apply

working on every feature except one.

I am writing several higher level VMs that need to call native javascript functions (unfortunately Function.prototype.call

is one of them), so I need a function apply

to pass this context and an array of arguments.

Updated: Seems like this is just some weird error message. I found this when I wanted to call a constructor with a variable number of arguments and explicitly pass this

which is the object instead of the expected function.

Perhaps below is a more realistic example:

function Fruit(name) {
  this.name = name;
}
var x = {};
Fruit.call(x, "Apple");
// I thought this would also work, but it throws above error message
(Fruit.call).apply(x, ["Apple"]);
// Should instead use the constructor directly
Fruit.apply(x, ["Apple"]);
// or
(Fruit.call).apply(someFunction, [x, "Apple"]);

      

+3


source to share


1 answer


You are getting the error because you are not passing an argument .apply

. Firefox throws a more reasonable error:

TypeError: Function.prototype.call raises incompatible undefined

It works fine in both browsers, if you actually pass the function to be called:



Window.call.apply(function foo() { console.log('foo'); });
      

Run code



Note. If you really want to apply a function Window

to an arbitrary object, it probably won't work. Host objects / functions are often more restrictive, especially if they are DOM related.

+2


source







All Articles