代码之家  ›  专栏  ›  技术社区  ›  Jacob George

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

  •  3
  • Jacob George  · 技术社区  · 11 年前

    我有以下课程

    Box类

    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 类的引用 收集 虽然我似乎得到了一份 newCollection 每次上课 类(每个框的长度不同)

    Array.each(newCollection.boxes, function (box) {
        console.log('*',box.getParent());
    });
    

    我是mootools的新手,尽管我已经阅读了文档,但这就是我最终编写代码的方式。在mootools中是否有一种更被接受的编码模式,我可以通过它引用 父母亲 ?

    这是 fiddle .

    1 回复  |  直到 11 年前
        1
  •  1
  •   Jibi Abraham    11 年前

    很容易错过。 setOptions ( docs ) 深度复制 options对象。只需设置 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);
    });