javascript - mootools/class/objectinstance 不起作用

标签 javascript mootools

我不知道为什么当我调用 a.get() 时得到的是“b”而不是“a”。有人可以帮助我吗?

var tclass = new Class({
initialize:function(n){
    this.options = Object.extend({'name' : n});
},
get:function(){
    return this.options.name;
}
});

a = new tclass('a');
b = new tclass('b');
a.get()  // b

最佳答案

您应该使用 Options 类作为 mixin 并使用 setOptions 来正确进行合并:

var tclass = new Class({
    Implements: [Options],
    initialize: function(n) {
        this.setOptions(n);
    },
    get: function() {
        return this.options.name;
    }
});


var a = new tclass({
    name: 'a'
});
var b = new tclass({
    name: 'b'
});
alert(a.get()); // a

话虽如此,在你的示例中,我得到了不同的响应 - 正如预期的 - 但通过 $merge 而不是扩展(合并确实取消链接): http://www.jsfiddle.net/dimitar/cqd8P/

但是这有什么意义,因为你没有 this.options 存在(你需要传递一个对象来扩展它/将它与另一个对象合并)。你也可以这样做:

this.options = {
    name: n
};

你真的想要this.setOptions

附:对于 mootools 1.11 Implements 的做法有所不同:

var tclass = new Class({
    initialize: function(n) {
        this.setOptions(n);
    },
    get: function() {
        return this.options.name;
    }
});

tclass.implement(new Options);

var a = new tclass({
    name: 'a'
});
var b = new tclass({
    name: 'b'
});
alert(a.get()); // a

关于javascript - mootools/class/objectinstance 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3777904/

相关文章:

javascript - 使用 Mootools 获取元素内的特定元素

JavaScript:确定图像类型

javascript - 我如何创建 dojo slider

javascript - 填充选择菜单 onChange

javascript - <td> 标签在注入(inject) MooTools Elements 时从文本中剥离

javascript - 替换mootools 1.3中的bindwithevent函数(从1.2升级)

javascript - 单击按钮将事件类添加到 Bootstrap 选项卡

javascript - jQuery:$(this) 与 this.$()

javascript - 在移动设备上使用 mootools 拖动

javascript - 如何使用 xmlhttprequest 对象的 post 方法发送数据