【发布时间】: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