将javascript普通对象转换为模型类实例 [英] convert javascript plain object into model class instance
本文介绍了将javascript普通对象转换为模型类实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要实现类似ODM的小型功能.我从数据库中获取普通的javascript对象,并且需要将其转换为模型类实例.假设模型看起来像这样:
I need to implement small ODM like feature. I get plain javascript object from database, and I need to convert it into my model class instance. Let's assume model looks like:
class Model{
constructor(){
this.a = '777';
---- whole bunch of other things ---
}
print(){
console.log(this.a);
}
}
因此,我需要将var a = {b:999, c:666}
转换为模型实例,并且能够在执行a.print()
后将调用a.print()
并将其放置在控制台中.该怎么做?
So I need convert var a = {b:999, c:666}
to instance of model and being able to call a.print()
after, and when a.print()
executed 777
should be placed in console. How to do that?
推荐答案
有一个简单的方法.只需将对象分配给instance(this)
There have a simple method. Just assign the object to instance(this)
class Model
{
constructor(obj){
Object.assign(this, obj)
}
print(){
console.log(this.a);
}
}
let obj = {a: 'a', b: 'b', c: 'c'}
let m = new Model(obj)
console.log(m)
m.print() // 'a'
这篇关于将javascript普通对象转换为模型类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文