【问题标题】:Reinstantiate custom class from string从字符串重新实例化自定义类
【发布时间】:2020-01-25 18:35:30
【问题描述】:

从持久数据结构中重新实例化类的最佳方法是什么?

当前在存储我 JSON.stringify() 时,它会在重新实例化时解析该字符串

 module.exports = class Player {
  constructor(str, isExistingInstance=false, rsn) {
    if(isExistingInstance) {
      try {
        parsedObject = JSON.parse(str)
        this.rsn = parsedObject.rsn 
        this.skills = parsedObject.skills
        this.kc = parsedObject.kc
      } catch (err) {
        console.log("Error instantiating object from exisiting instance. Expected JSON.stringify'd version of Player, Received: ", str)
      }
  } else {
    if(!rsn) throw new Error("Expected type of string for rsn, received: ", typeof(rsn));
  }
}

我不喜欢这种方法,因为您必须提供str,即使它不是现有实例。有人对如何改进有任何建议吗?

我目前的想法是类似这样的“builder”函数:

function buildNewPlayer(rsn) {
  new Player(null, false, rsn);
}

function buildExistingPlayer(str, rsn) {
  new Player(str, true, ""); 
}

这种方法看起来很乱或很脏,我觉得必须有一种更清洁的方法来处理重新实例化。

【问题讨论】:

  • 在类上有一个静态的fromJSON 方法。然后你可以做const player = Player.fromJSON(str)。该方法可以根据需要对属性设置进行所有解析。
  • 哦。听起来确实更干净。然后用const existingPlayer = new Player().fromJSON(str)之类的东西重新创建?
  • @FelixKling 我最喜欢你的建议。在我看来,使用静态方法是最干净的方法。如果您发布答案,我会接受它! :)

标签: javascript class ecmascript-6


【解决方案1】:

构造函数应该用于创建实例,将解析和构建移动到方法并在实例化类后调用它:

class Player {
  constructor() {
    this.rsn = null;
    this.skills = null;
    this.kc = null;
  }

  build(str, rsn) {
    if (rsn) {
      try {
        const parsedObject = JSON.parse(str);
        this.rsn = parsedObject.rsn;
        this.skills = parsedObject.skills;
        this.kc = parsedObject.kc;
      } catch (err) {
        console.log(
          "Error instantiating object from exisiting instance. Expected JSON.stringify'd version of Player, Received: ",
          str
        );
      }
    } else {
      throw new Error("Expected type of string for rsn, received: ", typeof rsn);
    }
  }
}

const str = '{"rsn": 123, "skills" : "a lot", "kc": "kc"}';

const playerOne = new Player();
playerOne.build(str, 123);

console.log(playerOne.skills);

【讨论】:

    猜你喜欢
    • 2012-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-23
    • 1970-01-01
    • 2023-03-22
    相关资源
    最近更新 更多