You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将ObjectLayer类实例currentVersion恢复到初始状态?

解决方案

核心逻辑是新增独立的存储空间保存初始版本的深拷贝,避免引用类型赋值导致备份被后续修改污染,具体实现步骤如下:

  • 在声明currentVersion的类中新增私有属性存储初始备份
  • 修改setVersion方法,赋值时同时写入初始备份
  • 新增重置方法,需要恢复时从备份中读取深拷贝赋值给currentVersion

完整代码示例:

export class ObjectLayer {
  id: number;
  name: string;
}

// 你业务逻辑所在的类
class YourBusinessClass {
  public currentVersion: ObjectLayer;
  // 新增私有属性存储初始版本备份
  private initialVersion: ObjectLayer;

  setVersion(object: ObjectLayer) {
    // 深拷贝服务端返回的原始对象作为初始备份
    this.initialVersion = JSON.parse(JSON.stringify(object));
    // 当前使用版本也使用拷贝值,避免修改影响服务端返回的原始对象
    this.currentVersion = JSON.parse(JSON.stringify(object));
  }

  // 新增重置方法,调用即可恢复初始版本
  resetToInitialVersion(): void {
    this.currentVersion = JSON.parse(JSON.stringify(this.initialVersion));
  }
}

如果你的ObjectLayer包含JSON序列化不支持的内容(比如类方法、循环引用、Symbol类型值),可以将深拷贝逻辑替换为浏览器原生structuredClone方法,或者自定义深拷贝函数即可。

内容的提问来源于stack exchange,提问作者user15423373

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 09:24:03