本文介绍了在ECMAScript 2015中调用Reflect.apply()对Function.prototype.apply()有什么好处吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道是否有任何理由要打电话:

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

Reflect.apply(myFunction, myObject, args);

而不是:

myFunction.apply(myObject, args);


推荐答案

您可以比较和。

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

基本上它们是等价的,但有区别:如果参数列表是 null undefined Function.prototype.apply 将调用该函数没有参数, Reflect.apply 将抛出。

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

另一个区别是,当你使用 func.apply ,您假设

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


  • func 是一个函数实例,即它继承自 Function.prototype

  • func 没有应用自己的属性,它会影响 Function.prototype.apply

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

但是 Reflect.apply 不需要那。例如,

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

这篇关于在ECMAScript 2015中调用Reflect.apply()对Function.prototype.apply()有什么好处吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 22:05