簡體   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