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/