Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function.prototype.apply doesn't work on Function.prototype.call in Chrome

Tags:

javascript

The title should be self explanatory, and I wonder 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 am surprised that apply works on every function except one.

I am writing some higher level VM that needs to call native javascript functions (sadly, Function.prototype.call is one of them), so I need the function apply to be able to pass my this context and array of arguments.

Updated: It seems that this is just some weird error message. I found this when I wanted to be able to call a constructor with variable number of arguments and passing this explicitly, which is an 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"]);
like image 720
Evan Sebastian Avatar asked Oct 30 '25 01:10

Evan Sebastian


1 Answers

You are getting the error because you are not passing an argument to .apply. Firefox throws a more reasonable error:

TypeError: Function.prototype.call called on incompatible undefined

It works fine in both browsers if you actually pass a function that should be called:

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

Note: If you actually want to apply the Window function to an arbitrary object, this probably won't work. Host objects/functions are often more restrictive, especially when it involves the DOM.

like image 176
Felix Kling Avatar answered Nov 01 '25 16:11

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!