ES6新手在這裏,在ES6
我試圖創建具有另一個類作爲其屬性的類克隆類。
我的問題是,我無法'克隆'它的屬性的類。
正如您在下面看到的,我的意圖是使用靜態方法Component.getAll()
僅返回在MyClass
實例內創建的項目。
我試過搜索一些東西,'mixins'出現了,但我不相信這會解決我的問題。
'use strict'
class Component {
constructor(id) {
this.id = id
Component.addItem(this)
}
static addItem(item) {
if (!this._items) {
this._items = []
}
this._items.push(item)
}
static getAll() {
return this._items
}
static getById(id) {
return this._items.find(i => i.id === id)
}
}
class MyClass {
constructor(things) {
//This is where my issue is.
this.Component = Component
things.forEach(t => new Component(t))
}
}
function showIds(divId, items) {
let ids = items.map(i => i.id)
document.getElementById(divId).innerHTML = ids.toString()
}
let a = new MyClass([1, 2, 3])
a.Component.getById(1) //-> returns what is expected
let aItems = a.Component.getAll() // -> [1,2,3]
showIds('a', aItems)
//I would like b.Component.getAll() to only output -> [4,5,6]
//But because i can;t 'clone' the class, Its just adding the items into the same bucket.
let b = new MyClass([4, 5, 6])
b.Component.getById(1) //-> should return undefined
let bItems = b.Component.getAll() // -> [1,2,3,4,5,6]
showIds('b', bItems)
<div id="a">
</div>
<div id="b">
</div>
聲明的Component
類中MyClass
似乎這樣的伎倆......但感覺像它使用require
或import
'use strict'
class MyClass {
constructor(things) {
class Component {
constructor(id) {
this.id = id
Component.addItem(this)
}
static addItem(item) {
if (!this._items) {
this._items = []
}
this._items.push(item)
}
static getAll() {
return this._items
}
static getById(id) {
return this._items.find(i => i.id === id)
}
}
this.Component = Component
things.forEach(t => new Component(t))
}
}
function showIds(divId, items) {
let ids = items.map(i => i.id)
document.getElementById(divId).innerHTML = ids.toString()
}
let a = new MyClass([1, 2, 3])
let aItems = a.Component.getAll() // -> [1,2,3]
showIds('a', aItems)
let b = new MyClass([4, 5, 6])
let bItems = b.Component.getAll() // -> [4,5,6]
showIds('b', bItems)
<div id="a">
</div>
<div id="b">
</div>
我會很感激任何建議!
所有的靜態集合實例是一個非常糟糕的主意,因爲你正在有效地防止所有這些垃圾收集。 – Bergi