Copy Javascript Object Prototype "Class"

I have a class User

. It has some properties like: name, id, password, etc.

I created 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 prototypes 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 well for me, and let me store my object as serialized JSON (in a couchbase with NodeJS) without including features in the object.

The problem arises when I get the object from the DB. It comes with all properties as stored, but I need to add back the functions. I tried using some functions extend

for the mixins I found, but they add the functions as ownProperties and so the next time I save the updated entry to the DB I get the saved functions.

How can I re-include the resulting object in an object of type User? To get the required class methods that also appear on the instance.

+3


source to share


1 answer


Several ways to do this:

this is roughly the same as your path:

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 implementation extend

instead Object.assign

(it is not available yet)

or you can change the implementation User

to keep all fields inside one property, which is an object

+5


source







All Articles