nzakas / understandinges6

Content for the ebook "Understanding ECMAScript 6"
5.45k stars 796 forks source link

Potential typo in 09 - Classes - Symbol.species property #453

Closed ronen-e closed 3 years ago

ronen-e commented 4 years ago

Where In chapter 9 - Classes under section The Symbol.species Property. see line 835

Problem

class MyArray extends Array {
    // empty
}

let items = new MyArray(1, 2, 3, 4),
    subitems = items.slice(1, 3);

console.log(items instanceof MyArray);      // true
console.log(subitems instanceof MyArray);   // true

In this code, the slice() method returns a MyArray instance. The slice() method is inherited from Array and returns an instance of Array normally. Behind the scenes, it's the Symbol.species property that is making this change.

Reason The example is meant to show the behavior of the Symbol.species property. In it the slice() method returns an instance of MyArray; not just a regular instance of Array as we would normally expect in ES5

Solution change the wording to something like:

In this code, the slice() method returns a MyArray instance. The slice() method is inherited from Array but returns an instance of MyArray whereas in ECMAScript 5 and earlier, we would receive an instance of Array. Behind the scenes, it's the Symbol.species property that is making this change.

nzakas commented 3 years ago

I don't believe your solution is correct. There's no reason to reference ES5 here. The goal of the example is to show that slice() automatically returns an instance of MyArray without any other changes. I agree the last sentence could use some tweaking. Maybe something like:

However, the constructor for the return value is read from the Symbol.species property, allowing for this change.