I'm trying to create a subclass of the Array object using the following code. It works perfectly when running in the browser. However, if I save this code in a .js file and include it with a <script>
tag, the .add()
method becomes undefined.
class CustomArray extends Array {
constructor(data) {
super(...data);
}
add(item) {
this.push(item);
}
}
const customArr = new CustomArray(['element1', 'element2']);
console.log(customArr); // -> ['element1', 'element2']
console.log(customArr.add); // -> undefined
When loading the page, the .add()
method is undefined. Yet, pasting the exact same code into the console makes it work.
What could be causing this?
Update: I also have Babel.js (v6.x) for transpilation, which turned out to be the issue, as explained by Fuechter in his answer.