I was messing around with ES6 Object Destructuring and started to try to define function properties through destructuring. For example:
const obj = {
test() {
return console.log('Hello World');
},
};
const { test } = obj;
test();
So then I started wondering if I could define native prototype methods through destructuring. However, this did not work as I expected. Here's an example of me trying to execute the Array.prototype.forEach() function through destructuring:
const arr = [1, 2, 3, 4, 5];
const { forEach } = arr;
forEach((num) => console.log(num))
As you can see, I get this error:
Uncaught TypeError: Array.prototype.forEach called on null or undefined
Does this not work for the same reason as this not corresponding to the usual value when inside an arrow function?
Array.prototype.hello = () => console.log(`Hello ${this}`);
[1, 2, 3].hello()
Array.prototype.hello = function() { return console.log(`Hello ${this}`); };
[1, 2, 3].hello()