search

Home  >  Q&A  >  body text

When should the Symbol.species method be triggered? javascript - When should the Symbol.species method be triggered?

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 time a 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?

漂亮男人漂亮男人2793 days ago525

reply all(1)I'll reply

  • ringa_lee

    ringa_lee2017-05-19 10:19:53

    You can read Teacher Ruan’s instructions http://es6.ruanyifeng.com/#do... The built-in Symbol value

    reply
    0
  • Cancelreply