引用(不是复制)一个类作为另一个类的成员- Mootools

Reference (not copy) a class as a member of another Class - Mootools

本文关键字:另一个 成员 Mootools 一个 复制 引用      更新时间:2023-09-26

我有以下类

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 ?

小提琴在这里。

容易错过setOptions (docs) 深度复制 options对象。只需在初始化Box后设置parent属性即可。我在这里张贴了一个稍微修改过的代码版本

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