简体   繁体   中英

Why does ES6 Object Destructuring not work with native javascript prototypes?

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()

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

This is not an issue with destructuring, this happens as the context is not set. You have taken the forEach reference out of the array and invoked it without any context.

Without destructuring if you do the same, you would get the same error:

 const arr = [1, 2, 3, 4, 5]; const forEach = arr.forEach; forEach((num) => console.log(num));

If you set the context as the array arr , explicitly after destructuring it would work:

 const arr = [1, 2, 3, 4, 5]; const { forEach } = arr; forEach.call(arr, (num) => console.log(num));

If you check the polyfill of Array#forEach you would see this line:

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

This is in fact the result you get, when you try to invoke the forEach without a context. This is required as the forEach needs an array context to work. As without the right context, how is the forEach going to know which array to iterate or how many elements are present in the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM