var map = {a: 1, b: []}; // simple object
var SomeClass = new Class({'map': map}); // class attribute
var sc = new SomeClass();
使用简单的对象,一切正常
console.log(map.hasOwnProperty('a')); // true
console.log(map.hasOwnProperty('b')); // true
console.log(Object.keys(map)); // ['a', 'b']
但是使用sc.map,不能使用标量值(int,boolean,string)
console.log(sc.map.hasOwnProperty('a')); // expected: true, returns: false
console.log(sc.map.hasOwnProperty('b')); // expected: true, returns: true
console.log(Object.keys(sc.map)); // expected: ['a', 'b'], returns: [b]
我意识到这是因为sc.map有一个__proto__属性
console.log(map.__proto__); // expected: empty Object console.log(sc.map.__proto__); // expected: the "map" Object
我认为这是一个最近的问题,因为我有大量的代码,有些东西因此而停止工作.我不想更改我的所有代码来解决这个问题,我猜想需要一些mootools补丁.
哇.所以源代码, https://github.com/mootools/mootools-core/blob/master/Source/Class/Class.js#L85,很多合并: https://github.com/mootools/mootools-core/blob/master/Source/Core/Core.js#L348-L369想要derefrence.优秀.
var map = {a: 1, b: []}; // simple object
var SomeClass = new Class({'map': map}); // class attribute
var sc = new SomeClass();
console.log(sc.map.b.length);
map.b.push('doge');
console.log(sc.map.b.length); // 0
console.log(map.b.length); // 1
map.a = 'doge';
console.log(sc.map.a); // 1
严肃地说,根本不是最近的变化,任何非原始人都被抄袭,不要惊慌失措.这是件好事.你可能不希望你的对象的原型因为它引用的东西而改变.
now. that being said, it’s weird where a ends up from. 07002 – I agree this is not ideal and is somewhat unexpected. filing an issue on GH, though don’t hold your breath. if it’s a recent change, it will be related to browser changes. Same code breaks in 1.3.2 and mootools 1.4.5 is quite old now and unchanged. The issue I filed on your behalf is here: 07003 – feel free to elaborate and add more usecases of where this is actually useful (I still don’t like passing objects into prototypes)
但是,如果您需要通过引用让对象拥有map对象并避免合并,则可以将引用放在构造函数方法中:
var map = {a:1},
foo = new Class({
initialize: function(){
this.map = map;
}
});
var bar = new foo();
map.a++;
console.log(bar.map.a); // 2
但如果你绝对必须打破常规并知道副作用,那么你可以.
var map = {a: 1, b: []}; // simple object
var SomeClass = new Class(); // class attribute
// avoid the derefrence rush, go prototypal manually
SomeClass.prototype.map = map;
var instance = new SomeClass,
other = new SomeClass;
console.log(instance.map.a); // 1
map.a++;
console.log(instance.map.a); // 2
// but also:
console.log(other.map.a); // 2
记住,MooTools类只是构造函数创建的糖,可以避免不必重复和非简洁的操作.它仍然是引擎盖下的javascript,你可以在顶部使用经典的原型模式.
