Reputation: 2578
The doc page of Reflect.apply()
on MDN web docs states:
In ES5, you typically use the Function.prototype.apply() method to call a function with a given this value and arguments provided as an array (or an array-like object).
Function.prototype.apply.call(Math.floor, undefined, [1.75]);
With
Reflect.apply
this becomes less verbose and easier to understand.
I'm confused. In ES5, I typically use (to keep the example above):
Math.floor.call(undefined, [1.75]);
Why should somebody use instead:
Function.prototype.apply.call(Math.floor, undefined, [1.75]);
P.S.: My question is not about Reflect.apply(myFunction, myObject, args);
Upvotes: 6
Views: 2352
Reputation: 1074208
It's possible to override the methods on a function, making apply
do something other than its default purpose:
function foo() {
console.log("This doesn't happen");
}
foo.apply = function() {
console.log("This happens instead.");
};
foo.apply({});
Also, back in the old days host-provided functions didn't always have those methods (but that's mostly not true anymore).
It's similar to the reason that people recommend using Object.prototype.hasOwnProperty.call(x, y)
[or the new Object.hasOwn(x, y)
] rather than x.hasOwnProperty(y)
. (But in that case, it also protects against the possibility that x
doesn't inherit from Object.prototype
, which is possible now. For instance, if x
is the result of Object.create(null)
or inherits from any object created that way.)
Upvotes: 9