-1

I've some problems to extend an JS array. These are my classes:

// ArrayList.js
export default class ArrayList extends Array {
  clear() {
    this.splice(0, this.length);
  }
}

// MyItem.js
export default class MyItem {
  constructor() {
    this._id = 0;
  }

  getID() {
    return this._id;
  }

  setID(value) {
    if (typeof value === 'number') {
      this._id = value;
    }
  }
}

// Test.js
import ArrayList from './ArrayList';
import MyItem from './MyItem';

let list = new ArrayList();

let item1 = new MyItem();
item1.setID(1);
list.push(item1);

let item2 = new MyItem();
item2.setID(2);
list.push(item2);

If I now execute:

list.forEach(function(item) {
  console.log(item.getID());
});

Everything works perfect but if I try to call my custom method I run into errors:

list.clear();
console.log(list.length);

The exception is:

TypeError: list.clear is not a function

+++ UPDATE +++

I use the test script with node.js:

node start.js

That's my start.js:

require('babel-register')({
    presets: [ 'env' ]
})
module.exports = require('./Test.js')

And then every class is stored in a separate JS file.

altralaser
  • 2,035
  • 5
  • 36
  • 55

1 Answers1

0

I don't like your import end exports. Try modules (https://nodejs.org/api/modules.html) and this should work without Babel in Node.

module.exports =  class MyItem {
   // class content 
}

module.exports =  class ArrayList extends Array {
    clear() {
        this.splice(0, this.length);
    }
}

// in the test file
const ArrayList = require('./ArrayList');
const MyItem = require('./MyItem');


Kamil Naja
  • 6,267
  • 6
  • 33
  • 47
  • Your solution works, so I accepted it but it not exactly match the import use case. – altralaser Apr 05 '19 at 19:01
  • If you want use imports, like in your example code, you must setup correctly babel. Here https://www.robinwieruch.de/minimal-node-js-babel-setup/ you can find good example how to do this. – Kamil Naja Apr 05 '19 at 19:12
  • But you wrote that using Babel (which I already configured) did not let you inherit any built-in class. That seems to be the typical chicken or the egg causality dilemma. I suspect the problem can only be solved by choosing the code you posted above or building a wrapper class for the array. – altralaser Apr 05 '19 at 21:53
  • I get your point. If you want new method in "array" class, maybe you can extends prototype of this class like here - https://stackoverflow.com/questions/948358/adding-custom-functions-into-array-prototype. In my opinion, better way is create some utils methods. For clearing data from array, method can get array as parameter end returns cleared array. – Kamil Naja Apr 06 '19 at 08:38