admin管理员组

文章数量:1384656

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 bees 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);

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 bees 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);

Share Improve this question edited Mar 25, 2019 at 18:40 Min-Soo Pipefeet asked Mar 25, 2019 at 15:34 Min-Soo PipefeetMin-Soo Pipefeet 2,6085 gold badges15 silver badges31 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 9

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 remend 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.)

本文标签: javascriptWhy should I call Functionprototypeapplycall(x) instead of xapply()Stack Overflow