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

问题描述 投票:2回答:3

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

javascript destructuring
3个回答
3
投票

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

enter image description here


2
投票

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

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

2
投票

您可以通过使用截取toObjectownKeys伪造对象进行解构的代理装饰目标来使您的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]
© www.soinside.com 2019 - 2024. All rights reserved.