javascript - 为什么我应该调用 Function.prototype.apply.call(x, ...) 而不是 x.apply(...)?

标签 javascript apply

The doc page MDN 网络文档上的 Reflect.apply() 指出:

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.

我很困惑。在 ES5 中,我通常使用(保留上面的示例):

Math.floor.call(undefined, [1.75]);

为什么有人应该改用:

Function.prototype.apply.call(Math.floor, undefined, [1.75]);


P.S.:我的问题不是关于 Reflect.apply(myFunction, myObject, args);

最佳答案

可以重写函数的方法,使 apply 做一些不同于其默认目的的事情:

function foo() {
  console.log("This doesn't happen");
}
foo.apply = function() {
  console.log("This happens instead.");
};

foo.apply({});

此外,在过去,主机提供的函数并不总是具有这些方法(但现在基本上不再是这样了)。

这类似于人们推荐使用 Object.prototype.hasOwnProperty.call(x, y) [或新的 Object.hasOwn(x, y) 的原因] 而不是 x.hasOwnProperty(y)。 (但在那种情况下,它也防止 x 不继承自 Object.prototype 的可能性,这现在是可能的。例如,如果 x Object.create(null) 的结果或继承自以这种方式创建的任何对象。)

关于javascript - 为什么我应该调用 Function.prototype.apply.call(x, ...) 而不是 x.apply(...)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55341350/

相关文章:

javascript - 读取粘贴的数据 onBeforePaste 或 onPaste

Python:将函数应用于groupby

javascript - 使用 Firebase 规则构建数据

javascript - 带有链接的褪色图像

javascript - 倒数约会的剩余天数?

r - apply() 没有按预期工作

python - 在 Pandas 中的相对行上应用函数

javascript - 阻止 FancyTree 复选框行突出显示为事件

r - R中多个固定参数的应用函数

R:行名、列名、暗号和名称适用