When I read the description of MDN, I encountered doubts. MDN describes this method like this
You may want to return Array objects on the extended array class MyArray. For example, when using methods such as map() that return the default constructor, you want these methods to return the parent's Array object instead of the MyArray object.
// demo class MyArray extends Array { static get [Symbol.species]() { return Array; // 1 } } var a = new MyArray(1, 2, 3); // 2 var mapped = a.map(x => x * x); // 3 console.log(mapped instanceof MyArray); // false console.log(mapped instanceof Array); // true
According to my understanding, this method will be triggered when creating an object, and the obtained object should also be an instance of the Array type. Debugging found that when the code was executed at point 2, it did not jump to point 1 for execution, but continued execution to point 1 when the map method at point 3 was executed. At this timea instanceof MyArray === true, a instanceof Array === true
. After the execution of 3 points, the output result in the code will be obtained.
When will this method be triggered? Why does a instanceof MyArray === true but mapped instanceof MyArray === false?
You can read Teacher Ruan’s instructions http://es6.ruanyifeng.com/#do... The built-in Symbol value