[英]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.