Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy Javascript "Class" Prototype to an Object

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.

like image 731
Vicenç Gascó Avatar asked Jan 09 '23 09:01

Vicenç Gascó


1 Answers

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

like image 156
vkurchatkin Avatar answered Jan 10 '23 22:01

vkurchatkin