Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 212
Jose Angel Avatar asked Nov 20 '15 17:11

Jose Angel


2 Answers

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.

like image 183
Sulthan Avatar answered Oct 22 '22 14:10

Sulthan


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.

like image 27
loganfsmyth Avatar answered Oct 22 '22 14:10

loganfsmyth