[英]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.