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

标签 javascript mootools

我有以下类(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/

相关文章:

javascript - 是否可以使用blade 将参数传递给tinymce.init 函数?

javascript - highcharts 定位器工具提示 - 一般 javascript

javascript - 如何使用大量 RSS 提高应用程序的速度

javascript - 嵌套 javascript 哈希的默认值

javascript - 用户使用 Firebase 身份验证登录后如何重定向?

javascript - 将一系列函数覆盖为 Promise

javascript - 如何仅在悬停时显示 CSS 过渡效果?

php 的 "setcookie"无法跨浏览器工作?

html - MooEditable : temporary disable editing

javascript - 在 JavaScript 中多次引用一个变量