我在搞乱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()