我有以下类(class)
盒子类
var Box = new Class({
Implements: [Options],
options: {
name: 'new',
weight: 0
},
initialize: function (options) {
this.setOptions(options);
},
getParent: function () {
return this.options.parent;
}
});
集合类
var Collection = new Class({
Implements: [Options],
options: {
boxes: []
},
boxes: [],
initialize: function (options) {
var self = this;
this.setOptions(options);
Array.each(this.options.boxes, function (box) {
self.boxes.push(new Box({
parent: self,
name: box.name,
weight: box.weight
}));
});
}
});
创建时,我将 Collection
类(作为 parent
)传递给 Box 类。
var newCollection = new Collection({
boxes: [
{
name: 'A',
weight: 9
},
{
name: 'B',
weight: 3
},
{
name: 'C',
weight: 2
},
{
name: 'D',
weight: 5
},
{
name: 'E',
weight: 7
}
]
});
我希望 Box
类中的 parent
是对 Collection
类的引用而不是副本,尽管看起来我每次创建 Box
类时都获取 newCollection
类的副本(每个盒子的长度不同)
Array.each(newCollection.boxes, function (box) {
console.log('*',box.getParent());
});
我是 mootools 的新手,尽管我已经阅读了文档,但这是我最终编写代码的方式。 mootools 中是否有更可接受的编码模式,我可以通过它来引用 parent
?
这是 fiddle .
最佳答案
容易错过。 setOptions
( docs ) 深度复制选项对象。只需在初始化后设置 Box 的 parent
属性。我发布了您的 code here 的略微修改版本
Array.each(this.options.boxes, function (box) {
var nB = new Box({
name: box.name,
weight: box.weight
});
// Note the difference
nB.parent = self;
self.boxes.push(nB);
});
关于javascript - 引用(而不是复制)一个类作为另一个类的成员 - Mootools,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15386662/