[英]JavaScript method to over-ride default behaviour of object destructuring
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.