【问题标题】:Is there any way in which we can convert plain object to class object?有什么方法可以将普通对象转换为类对象?
【发布时间】:2020-11-27 23:24:45
【问题描述】:

我有一个Wallet 类,wallet 是这个类的一个实例。 我不得不JSON.stringify(wallet) 将它保存在一个文件中。现在,当我执行JSON.parse(JSON.stringify(wallet)) 时,它就不再是Wallet 的实例了。

如何将此普通对象从JSON.parse 转换为intanceof Wallet

【问题讨论】:

标签: javascript json class object stringify


【解决方案1】:

您可以使用Object.assign(target, source) 将普通对象的属性分配给您的实例。

请务必阅读链接的 MDN 文档中提到的所有问题,尤其是在您有嵌套对象的情况下。

let plain = { 
   foo : 'bar',
   count : 42
}
class Complex {
    constructor() {
        this.foo = 'hello';
        this.count = 10; 
    }
    
    getCount() {
        return this.count;
    }
    
    getFoo() {
        return this.foo;
    }
}
let test = new Complex();
console.log(test.getFoo());
console.log(test.getCount());
console.log('==== assigning plain object ===');

Object.assign(test, plain);

console.log(test.getFoo());
console.log(test.getCount());

【讨论】:

  • 我用的是椭圆曲线模块,对象真的很大。所以,这样声明不会是一个可行的选择。
  • 请发布您的普通对象的示例。
【解决方案2】:

只需使用Object.assign(),就像这样:

const walletLiteral = JSON.parse(response);
const walletInstance = Object.assign(new Wallet(), walletLiteral);

【讨论】:

    猜你喜欢
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    • 2016-09-14
    • 2016-08-30
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 2012-08-02
    相关资源
    最近更新 更多