Extending built-in natives in ES6 with Babel

I'm using Babel for extend my class with the built-in native Array

class NewArray extends Array {
  first() {
    return this[0];
  }
}

var a = new NewArray(1, 2, 3);
console.log(a.length); // 3
console.log(a); // [ 1, 2, 3 ]
console.log(a.first()); // trigger error

In a.first(), I'm getting this error:

console.log(a.first());
              ^ 

TypeError: a.first is not a function

Should I do something more to extend a built-in native?

Thanks!

Answers:

Answer

Extending native classes is not supported by Babel. It was removed in version 5.2.17 (see this commit)

It was removed because it was not working properly, see the bug: https://phabricator.babeljs.io/T1424

It's unlikely it will be ever added because it's not a feature that can be simulated. We will have to wait for native support in browsers (some already support it now in experimental mode). That also means it will currently behave differently in different browsers.

Answer

Babel by default cannot handle extending builtin types. On Babel 6, you can now do this with https://www.npmjs.com/package/babel-plugin-transform-builtin-extend by doing

"plugins": [
    ["transform-builtin-extend", {
        globals: ["Array"]
    }]
]

Keep in mind that this can be an issue on older environments like older IE, so whether you should extend builtin types depends a bit on whether or not you care about that.

Answer

Although I don't see why you get the error (I cant reproduce it) you will not get what you intended to get from the first() function.

What you can do is this:

   class NewArray extends Array {
      constructor(){
        super();
        this.first = function(){ return this[0]; }
      }
    }

    var a = new NewArray();
    a.push(10);
    console.log(a.first()); // 10

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.