Javascript 在es6中克隆类
这里是es6新手 我正在尝试创建一个类,该类的属性为另一个类 我的问题是我无法“克隆”类的属性 正如您在下面看到的,我打算使用Javascript 在es6中克隆类,javascript,class,ecmascript-6,Javascript,Class,Ecmascript 6,这里是es6新手 我正在尝试创建一个类,该类的属性为另一个类 我的问题是我无法“克隆”类的属性 正如您在下面看到的,我打算使用Component.getAll()static方法只返回在MyClass实例中创建的项 我试着四处寻找一些东西,“mixins”出现了,但我不相信这能解决我的问题 “严格使用” 类组件{ 建造师(id){ this.id=id 组件.附加项(此) } 静态附加项(项){ 如果(!此.\u项){ 此项。_items=[] } 此.\u项目。推送(项目) } 静态getA
Component.getAll()
static方法只返回在MyClass
实例中创建的项
我试着四处寻找一些东西,“mixins”出现了,但我不相信这能解决我的问题
“严格使用”
类组件{
建造师(id){
this.id=id
组件.附加项(此)
}
静态附加项(项){
如果(!此.\u项){
此项。_items=[]
}
此.\u项目。推送(项目)
}
静态getAll(){
退回此物品
}
静态getById(id){
返回此.\u items.find(i=>i.id==id)
}
}
类MyClass{
建造师(事物){
//这就是我的问题所在。
this.Component=Component
forEach(t=>newcomponent(t))
}
}
函数showIds(divId,items){
让id=items.map(i=>i.id)
document.getElementById(divId).innerHTML=ids.toString()
}
设a=newmyclass([1,2,3])
a、 getById(1)/->返回预期的内容
设aItems=a.Component.getAll()/->[1,2,3]
showIds('a',aItems)
//我希望b.Component.getAll()只输出->[4,5,6]
//但因为我可以;“克隆”类,只是将项目添加到同一个bucket中。
设b=newmyclass([4,5,6])
b、 getById(1)/->应返回未定义的
让bItems=b.Component.getAll()/->[1,2,3,4,5,6]
showIds('b',bItems)
正如您在下面看到的,我打算使用Component.getAll()
static方法只返回在MyClass
实例中创建的项
问题是只有一个组件
类和一个组件。MyClass
(间接)的每个实例都访问相同的组件
在MyClass中声明组件类似乎可以做到这一点
是的,因为现在每个实例都有自己的组件
类
但使用require
或import
我不知道怎么做
然而,我同意在另一个类的构造函数中创建一个类似乎很奇怪。也许跟踪组件
实例不应该是组件
本身的一部分,而应该是MyClass
的一部分
无论您选择何种解决方案,每个实例都必须有自己的数组,以便跟踪其组件
实例。静态方法针对每个类设计为单一的。如果您不希望它们是单一的,您可能不需要静态方法
您可以添加一个名为ComponentsCollection
的额外类,该类为您执行Component
跟踪。让我们从Component
class Component {
constructor(id) {
this.id = id
}
}
class ComponentsCollection {
constructor() {
this._components = [];
}
createComponent(id) {
const component = new Component(id);
this.components.push(component);
return component;
}
getAll() {
return this._components;
}
}
然后您可以在MyClass
中实例化componentscolection
,并使用它创建组件
class MyClass {
constructor(things) {
this.collection = new ComponentsCollection();
things.forEach(t => this.collection.createComponent(t));
}
}
看看这个:
let a = new MyClass([1, 2, 3])
console.log(a.collection.getAll().map(i => i.id)) // [1,2,3]
let b = new MyClass([4, 5, 6])
console.log(b.collection.getAll().map(i => i.id)) // [4,5,6]
放弃“可能”。对所有实例进行静态收集是一个非常糟糕的主意,因为这样可以有效地防止对所有实例进行垃圾收集。太棒了。谢谢这正是我想要的,一个“收集管理器类”。