dwhieb dwhieb - 3 months ago 7
Javascript Question

cannot add method to Array subclass

I'm attemping to subclass the Array object with the code below. If you run the code in the browser, it works fine. However, if I place this code in a .js file, and include that file with a

<script>
tag, the
.add()
method is undefined.



class Collection extends Array {
constructor(data) {
super(...data);
}

add(model) {
this.push(model);
}

}

const coll = new Collection(['item1', 'item2']);

console.log(coll); // -> ['item1', 'item2']
console.log(coll.add); // -> undefined





When I load the page,
.add()
is undefined. But when I copy-paste the exact same code into the console, it works.

What's going on?

Update
I'm also using Babel.js (v6.x) to transpile, and this turned out to be the problem, as Fuechter explains in his answer.

Answer

Fix:

class Collection extends Array {
  constructor(data) {
    super(...data);
    this.add = function(model) {
      this.push(model);
    }
  }
}

Why:

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.

Reference: Link