审查生成的只读发票视图

来自 Proxy 与 Reflect
Node 24 高级 12分钟 找出 4处问题

审查这个生成式只读发票代理。

提供带可枚举虚拟 total 的只读发票视图,同时保留普通 receiver 行为与代理不变量。

JavaScript
function createReadonlyInvoice(target) {
  return new Proxy(target, {
    get(target, key) {
      console.log(`read ${key}`);
      if (key === "raw") return target;
      const value = Reflect.get(target, key, target);
      return typeof value === "function" ? value.bind(target) : value;
    },
    set() {
      throw new TypeError("read only");
    },
    ownKeys(target) {
      return [...Reflect.ownKeys(target), "total"];
    },
    getOwnPropertyDescriptor(target, key) {
      if (key === "total") {
        return { configurable: true, enumerable: true };
      }
      return Reflect.getOwnPropertyDescriptor(target, key);
    },
  });
}

生成代码仅作示例,不代表任何特定模型

在试验场中打开
报告错误