我有一个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字符串 恢复 这个类的实例的方法?
JSON 并不能恢复 class 的实例,看看 JSON 规范。