I have a created a class User
. It has some properties like: name, id, password, etc.
I've set up a constructor like:
function User(name1, email, password) {
this.name = name1;
this.id = __GUID();
this.type = __TYPE;
this.addNewEmail(email);
this.password = (new Password).createFromRawPassword(password).crypt;
}
And some prototype functions like:
User.prototype.save = function(cb, callback) {
return cb.bucket.upsert(this.id, this, function(err, res) {
if (callback == null) {
return callback(err, res);
}
});
};
User.prototype.addNewEmail = function(email) {
this.emails = this.emails || [];
return this.emails.push(email);
};
This works pretty nice for me, and let's me store my object as serialized JSON (in a couchbase database with NodeJS) without including in the object the functions.
The problem comes when I get the object from DB. It comes with all the properties, as stored, but I need to add back the functions. I have tried to use some extend
functions for mixins that I found, but they add the functions as ownProperties, and therefore, next time I save the updated record to DB, I get the functions saved.
How can I turn the received object into a object of type User again? To get the required methods of the class appearing also on the instance.
Multiple ways to do it:
this is roughly the same as your way:
Object.setPrototypeOf(instance, User.prototype)
you can instantiate a new object and copy properties:
var obj = Object.assign(Object.create(User.prototype), instance);
you can use any extend
implementation instead of Object.assign
(it's not available natively yet)
or you can change your User
implementation to store all fields inside of a single property, which is object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With