Babel can't properly extend Array?

时间:2016-10-20 19:45:17

标签: javascript ecmascript-6 babeljs

I am trying to extend the Array in native JS. But not just modifying the prototype. I thought I'd give it a shot with the new class es2015 syntax.

Trying it out native (chrome already supports it - yay ヽ(´▽`)ノ) and it all works just fine. Switching over to Babel for better support, it stops working. After trying a bit, I saw, that none of the methods are available on the new Object. Test code:

class CustomList extends Array {
  constructor(...elms) {
    super(...elms);

    this.testprop = "test";
  }

  customMethod(a) {
    console.log(a, this);
  }
}

(test in babel)

1 个答案:

答案 0 :(得分:3)

Babel.js can't extend the built-in classes properly:

Built-in classes such as Date, Array, DOM etc cannot be properly subclassed due to limitations in ES5 (for the es2015-classes plugin). You can try to use babel-plugin-transform-builtin-extend based on Object.setPrototypeOf and Reflect.construct, but it also has some limitations.

-- https://babeljs.io/docs/usage/caveats/#classes