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);
}
}
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?
I would suggest rewriting your class to store all its properties in a single JS object
this.props
and accept this object in its constructor:Then you'll be able to store
this.props
in your database as a plain JS object and then use it to easily recreate corresponding class instance:Though, if you don't want to move all properties to
this.props
, you could useObject.assign
to keep your object plain:But I would recommend using the former approach, because it'll keep you safe from name collisions.
How about this?:
You'd be basically creating a new instance of Model from it's prototype and assigning your new properties to it. You should be able to call
print
as well.Just like G_hi3's answer, but it "automates" the creation of the properties object
If I understand the question correctly, you can export a factory function and make use of
Object.assign
to extend your baseModel
:And call it like:
Babel REPL Example
Or, of course, you could forego the factory and pass
a
in as a parameter (or rest parameters) to the constructor but it depends on your preferred coding style.There have a simple method. Just assign the object to instance(this)