简体   繁体   中英

Extending array fails in JavaScript ES6

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.

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');


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM