Batmoose Batmoose - 1 month ago 16
Javascript Question

Inheriting from Array

I am trying to inherit all of

Array
's methods without using ES6
class
syntactic sugar. Additionally, I want methods like
new MyArray().map()
to return instances of
MyArray
.

Simple illustration of my problem:

class MyArrayES6 extends Array{}

new MyArrayES6().slice() instanceof MyArrayES6 //true

function MyArray(){}
MyArray.prototype = Object.create(Array.prototype)
MyArray.prototype.constructor = MyArray
MyArray[Symbol.species] = MyArray //Doing this doesn't affect the outcome

new MyArray().slice() instanceof MyArray //false, to my suprise!


A more complete code example
edit: Gave clearer example

Answer

The problem is that ArraySpeciesCreate does not use @@species when the object is not an array.

And if you don't use extends Array, instances won't be arrays by default.

If you really want it to work, you can still return a real array with a modified [[Prototype]]:

function ArraySub(){
  return Object.setPrototypeOf([], ArraySub.prototype);
}
ArraySub.prototype = Object.create(Array.prototype)
ArraySub.prototype.constructor = ArraySub
ArraySub[Symbol.species] = ArraySub;
console.log( new ArraySub().slice() instanceof ArraySub );

But that will hurt performance so bad. Better use extends Array.

Comments