我不知道为什么当我调用 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/