gpt4 book ai didi

Mootools 和 object.__proto__

转载 作者:行者123 更新时间:2023-12-05 01:06:18 24 4
gpt4 key购买 nike

Object.each , Object.keys , ... 当我尝试与作为类属性的对象一起使用时无法正常工作,请检查 this example :

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__属性(property)
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

想要取消引用。优秀的。

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

说真的,根本不是最近的变化,任何非原始人都是 copied进来,不要 panic 。这是一件好事。你可能不希望你的对象的原型(prototype)会因为它在外部引用的东西而改变。

now. that being said, it's weird where a ends up from. http://jsfiddle.net/mMURe/2/ - 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: https://github.com/mootools/mootools-core/issues/2544 - 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,您可以在上面使用经典的原型(prototype)模式。

关于Mootools 和 object.__proto__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20158847/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com