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

没有。规范 requires the right hand side to resolve to a value that can be converted to an object via ToObject,它只是 returns 对象本身,如果它被传递一个(即没有调用对象上的特殊方法将其转换为其他东西)。

如果你使用数组解构,那会起作用:

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

您可以通过使用拦截 ownKeysget 伪造对象进行解构的代理来装饰目标,从而使您的 toObject 正常工作:

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]