繁体   English   中英

用于覆盖对象解构的默认行为的JavaScript方法

[英]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魔术方法。

不。 规范要求右侧解析为可以通过ToObject转换为对象的值,如果传递了对象,则只返回对象本身(即,调用对象时没有特殊方法将其转换为其他对象) 。

在此输入图像描述

如果您使用数组解构,那将是有效的:

 const [a, b] = {
   *[Symbol.iterator]() {
     yield "some"; yield "stuff";
   }
};

你可以让你toObject工作的意图来装饰与拦截代理目标ownKeysget为解构虚假的对象:

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM