Javascript class如何从json优雅的恢复class的实例

我有一个JavaScript 的类为了简单说明问题所在,我把类的其它方法什么的都去掉了,只保留了一个getter

class Item {
  constructor (itemid, type = 'a') {
    this.type = type
    this.itemId = itemid
    this.hasChild = false
    this.child = null
  }
  get itemUrl () {
      return `https://www.xxx.com/?id=${this.itemId}`
  }
}

class Child {
  constructor (names) {
    this.names = names
  }
  
  get price() {
    return this.names + ' hello world'
  }
}

let i =new Item(123)
i.hasChild = true
i.child = new Child('abc')
console.log(i)

let json = JSON.stringify(i)

let j = JSON.parse(json)
j.child = Object.assign(new Child, j.child)
let b= Object.assign(new Item, j)
console.log(b.itemUrl)
console.log(b.child.price)

在线运行地址:
http://babeljs.io/repl/#?babi...
如果没有Object.assgin的操作,从JSON.parse中恢复的javascript 对像实例是Object 这样就没法,访问getter方法
为了从JSON中恢复类的实例,我用了两次Object.assign
有没有更优雅的方式来实现从json字符串 恢复 这个类的实例的方法?

阅读 6.1k
2 个回答

JSON 并不能恢复 class 的实例,看看 JSON 规范

JSON建构于两种结构:

  • “名称/值”对的集合(A collection of name/value pairs)。不同的语言中,它被理解为对象(object),纪录(record),结构(struct),字典(dictionary),哈希表(hash
    table),有键列表(keyed list),或者关联数组 (associative array)。
  • 值的有序列表(An ordered list of values)。在大部分语言中,它被理解为数组(array)。
...
let j = JSON.parse(json)
Object.setPrototypeOf(j, Item.prototype)
Object.setPrototypeOf(j.child, Child.prototype)

这里只提供另外一种思路,构造方法中含有属性定义等语句则无法使用这种方式还原。
于是最稳妥的方案只能是—— 1、先构造实例,2、json对象属性一一填回。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题