JavaScript Babel 编译 ES6 的 class extends Array 时,无法获取方法,求助

dxcqcv · 2016年11月20日 · 最后由 dxcqcv 回复于 2016年11月22日 · 7128 次阅读

代码如下


class MyCoolArray extends Array {
     first() { return this[0];}
  }
var a = new MyCoolArray(1,2,3);
console.log(a.first());// get error 'a.first is not a function'

谁知道为什么 first 无法执行?谢谢

babel 在线 https://babeljs.io/repl/#?babili=false&evaluate=true&lineWrap=false&presets=es2015%2Ces2015-loose%2Ces2016%2Ces2017%2Clatest%2Creact%2Cstage-0%2Cstage-1%2Cstage-2%2Cstage-3&code=class%20MyCoolArray%20extends%20Array%20%7B%0A%20%20first%20%7B%20return%20this%5B0%5D%3B%7D%0A%20%7D%0A%0Avar%20a%20%3D%20new%20MyCoolArray(1%2C2%2C3)%3B%0A%0A%0Aconsole.log(a.first)%3B()

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/

需要 登录 后方可回复, 如果你还没有账号请 注册新账号