ES6类代理不可变

问题描述 投票:1回答:1

嘿,我正在尝试创建一个类实例,这是不可变对象。所以我想使用代理。

我希望每次开发人员尝试更改对象属性时,都会从当前对象深度克隆新对象。结果将是这个带有变化的新对象。重要的是,课程原则将保持可用。

例:

class Men{
  constructor(name){
    this.schema = {prop: {innerProp:{}}}; 
    this.name = name;
  }
set newName(name){
    this.name = name;
  }
}

var handler = {
  set (target, key, value) {
      target =  new Proxy(_.cloneDeep(target), this);
      target[key] = value;
      return target // Return the new obj with the change
    }
};

let jeson = new Men("jeson");

let jesonProxy = new Proxy(jeson, handler);

// Taking the new jeson proxy with the change
let newJesonProxy = (jesonProxy.schema = {newProp: {newInnerProp: {}}});

提前致谢。

proxy ecmascript-6 es6-class
1个回答
2
投票

不,你不能为此使用代理,也不能使用setter。它们不允许您更改分配的结果。使用普通方法创建更改的实例,并简单地冻结对象。

class Man {
  constructor(name) {
    this.schema = {prop: {innerProp:{}}}; 
    this.name = name;
    Object.freeze(this);
  }
  withName(name) {
    return new this.constructor(name);
  }
}

const x = new Man("");
const y = x.withName("jeson");
© www.soinside.com 2019 - 2024. All rights reserved.