繁体   English   中英

在 JavaScript ES6 中扩展数组失败

[英]Extending array fails in JavaScript ES6

我在扩展 JS 数组时遇到了一些问题。 这些是我的课程:

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

如果我现在执行:

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

一切正常,但如果我尝试调用我的自定义方法,我会遇到错误:

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

例外是:

TypeError: list.clear is not a function

+++ 更新 +++

我将测试脚本与 node.js 一起使用:

node start.js

那是我的 start.js:

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

然后每个类都存储在一个单独的 JS 文件中。

我不喜欢你的进口端出口。 尝试模块( https://nodejs.org/api/modules.html ),这应该在 Node.js 中没有 Babel 的情况下工作。

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


暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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