JS中是否有一种方法可以在对象进行解构时覆盖对象的默认行为?
// Normally destructing lifts properties from an object
const foo = {
a: 1,
b: 2,
};
const { a, b } = foo; // a = 1, b = 2
// I would like to have a method return the properties to be
// destructured
const bar = {
toObject: () => {
return { a, b };
},
};
const { a, b } = bar; // a = undefiner, b = undefined
我知道我可以简单地使用const { a, b } = bar.toObject();
,但这要求对象的消费者知道它的内部是如何工作的,并打破了最不惊讶的原则。
我能想到的最接近我想要的是toJSON
魔法。
如果您使用数组解构,那将是有效的:
const [a, b] = {
*[Symbol.iterator]() {
yield "some"; yield "stuff";
}
};
您可以通过使用截取toObject
和ownKeys
伪造对象进行解构的代理装饰目标来使您的get
按预期工作:
let withToObject = obj => new Proxy(obj, {
ownKeys(o) {
return Object.keys(o.toObject())
},
get(o, prop) {
return o.toObject()[prop]
}
});
let bar = withToObject({
aa: 11,
bb: 22,
cc: 33,
toObject() {
return {
a: this.aa,
b: this.bb
};
}
});
const {a, b} = bar;
console.log(a, b)
当然,这不仅会影响解构,还会影响与对象的任何其他交互,例如序列化,因此您必须采取措施使这些工作也起作用。例如,要支持JSON,请修补get
,如下所示:
get(o, prop) {
if (prop === 'toJSON')
return () => o; // or o.toObject(), whatever fits better
return o.toObject()[prop]