1

I have two class Test0 and Test1, the both classes are inherited from Array. For Test0 I use ES6 syntax, for Test1 ES5.

class Test0 extends Array {
    constructor(...args) {
        super(...args)
        this.test = 'this is my array'

    }
}

function Test1(...args) {
    Array.call(this, ...args)
}


// Test1.prototype = Object.create(Array.prototype)
Object.setPrototypeOf(Test1.prototype, Array.prototype)
Object.setPrototypeOf(Test1, Array)
Test1.prototype.constructor = Test1


const a = new Test0(1, 2)
const b = new Test1(1, 2)

console.dir(a, b)

For Test0 I get the expected result: Test0(2) [ 1, 2 ], but for Test1 I get :Test1 {}. Why is this happening? How can I get a result like in ES6 using ES5?

  • 2
    You cannot subclass Array the old way. It just doesn't work, never did. It was an added feature in ES6 to make Array subclassable when using ES6 classes. – jfriend00 Nov 22 '20 at 19:59
  • I don't how to do it, but have one idea: http://js2.coffee/ in the right editor write "class Test extends Array" and you'll receive es5 version of it on the left. – user2541867 Nov 22 '20 at 20:10
  • 1
    http://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array/, https://stackoverflow.com/questions/33369131/is-it-possible-to-inherit-old-style-class-from-ecmascript-6-class-in-javascript – Bergi Nov 22 '20 at 21:21

0 Answers0