Extending built-in natives in ES6 with Babel
Asked Answered
F

3

17

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!

Flowing answered 20/11, 2015 at 17:27 Comment(2)
This is likely a limitation of Babel and/or browsers, since extending native classes is not supported yet and cannot really be simulated.Dimaggio
Felix thanks for clarificationFlowing
M
17

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.

Menses answered 20/11, 2015 at 22:26 Comment(2)
Thanks Sulthan, it is an error from babel, hope for next babel's update they can fix that. thanks againFlowing
See my answer for the suggested approach on Babel 6.Chacma
C
12

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.

Chacma answered 7/9, 2016 at 18:25 Comment(0)
E
0

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
Emotionality answered 20/11, 2015 at 17:35 Comment(4)
Could you explain? What's wrong in OP's code? Is it a problem with ES6 or a problem with babel? This looks more like a workaround.Menses
"The this[0] in your case is referring to the this of the first() function." What does that mean? "So the this[0] in your case should be simply not defined." Why not? The OP clearly initializes the array with three elements.Dimaggio
@AvraamMavridis Unfortunately it's not clear at all.Menses
I cant really reproduce the error, you can "unapprove" the answer if someone else can provide a better explanation.Emotionality

© 2022 - 2024 — McMap. All rights reserved.