Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any benefit to call Reflect.apply() over Function.prototype.apply() in ECMAScript 2015?

I am just wondering if there is any good reason to call:

Reflect.apply(myFunction, myObject, args); 

instead of:

myFunction.apply(myObject, args); 
like image 811
madox2 Avatar asked Jan 10 '16 15:01

madox2


People also ask

What is the difference between using call () and apply () to invoke a function with multiple arguments?

The Difference Between call() and apply() The difference is: The call() method takes arguments separately. The apply() method takes arguments as an array. The apply() method is very handy if you want to use an array instead of an argument list.

When to use reflect in JS?

Reflect is a built-in object that provides methods for JavaScript operations that are interceptable. It is not a function object and it does not have a construct internal method. This means that you cannot invoke Reflect objects as functions or even use them with the new operator.

What does apply () do in JavaScript?

The apply() method allows an object to borrow the method of another object without duplicating the code. The server object doesn't have the turnOn() and turnOff() methods. In this example, the server object borrows the turnOn() method of the computer object.

What is the use function prototype apply method?

prototype. apply() The apply() method calls the specified function with a given this value, and arguments provided as an array (or an array-like object).


1 Answers

You can compare the definition of Function.prototype.apply and Reflect.apply in the spec.

Basically they are equivalent, but there is a difference: if the arguments list is null or undefined, Function.prototype.apply will call the function with no arguments, and Reflect.apply will throw.

function func() {   return arguments.length; } func.apply(void 0, null); // 0 Reflect.apply(func, void 0, null); // TypeError: null is not a non-null object 

Another difference is that, when you use func.apply, you assume

  • func is a Function instance, i.e. it inherits from Function.prototype
  • func has no apply own property which would shadow Function.prototype.apply

But Reflect.apply doesn't require that. For example,

var obj = document.createElement('object'); typeof obj; // "function" -- can be called obj.apply; // undefined -- does not inherit from Function.prototype Reflect.apply(obj, thisArg, argList); // -- works properly 
var func = a => a; func.apply = a => 0; func.apply(void 0, [123]); // 0 -- Function.prototype.apply is shadowed by an own property Reflect.apply(func, void 0, [123]); // 123 -- works properly 
like image 189
Oriol Avatar answered Sep 25 '22 05:09

Oriol