2

我在搞乱ES6 对象解构并开始尝试通过解构来定义函数属性。例如:

const obj = {
  test() {
    return console.log('Hello World');
  },
};

const { test } = obj;
test();

于是我开始想我是否可以通过解构来定义原生原型方法。然而,这并没有像我预期的那样奏效。Array.prototype.forEach()这是我尝试通过解构执行函数的示例:

const arr = [1, 2, 3, 4, 5];

const { forEach } = arr;
forEach((num) => console.log(num))

如您所见,我收到此错误:

未捕获的类型错误:Array.prototype.forEach 调用 null 或未定义

this这与在箭头函数内不对应于通常值的原因相同吗?

Array.prototype.hello = () => console.log(`Hello ${this}`);
[1, 2, 3].hello()

Array.prototype.hello = function() {  return console.log(`Hello ${this}`); };
[1, 2, 3].hello()

4

1 回答 1

3

于是我开始想我是否可以通过解构来定义原生原型方法。然而,这并没有像我预期的那样奏效。这是我尝试通过解构执行 Array.prototype.forEach() 函数的示例

这不是解构的问题,这是由于未设置上下文而发生的。您已从forEach数组中取出引用并在没有任何上下文的情况下调用它。

如果你这样做,如果不进行解构,你会得到同样的错误:

const arr = [1, 2, 3, 4, 5];

const forEach = arr.forEach;
forEach((num) => console.log(num));

如果将 context 设置为 array arr,则在解构后显式地将其工作:

const arr = [1, 2, 3, 4, 5];

const { forEach } = arr;
forEach.call(arr, (num) => console.log(num));

如果你检查你的polyfillArray#forEach你会看到这一行:

if (this == null) { throw new TypeError('Array.prototype.forEach called on null or undefined'); }

forEach当您尝试在没有上下文的情况下调用时,这实际上是您得到的结果。这是必需的,因为forEach需要数组上下文才能工作。如果没有正确的上下文,如何forEach知道要迭代哪个数组或数组中有多少元素。

于 2020-10-13T11:53:24.697 回答