Home > Net >  Construct an object that has member functions from an object that has no member function with their
Construct an object that has member functions from an object that has no member function with their

Time:12-17

I am trying to build a javascript app with a document database that can store and retrieve object data (provided as api) without function members.

Now I have a class which have many properties and some functions as prototype.

Project: function(){
  this.a= 'abc';
  this.f = function(){
    console.log(this.a);
  }
}
//object from the databse
p0 = {
  a: 'abc';
}

I want to convert a plain object to an object with member function usable.

When I try something like this, it won't work:

// It won't work:
// for it needs a map that have many properties such as writable etc.
var pobj = Object.create(new Project(), p0);

I tried to search this question with different keywords on the internet, but I didn't find one related.

CodePudding user response:

The function you probably want to use is Object.assign.

So you can use Object.create to create an instance of the class (using the prototype), then assign the values from the data onto the new instance and then call the constructor (make sure to not override the values).

function Project() {
  if (this.foo === undefined) this.a = 'foobar';
  return this;
}

Project.prototype.print = function() {
  console.log(this.foo);
};

var data = {
  foo: 'bar'
};

var obj = Object.create(Project.prototype); // empty instance
obj = Object.assign(obj, data); // copy data
obj = obj.constructor(); // start constructor

obj.print();

Alternatively you could create a new instance using the new operator and then assign the data.

function Project() {
  this.a = 'foobar';
  return this;
}

Project.prototype.print = function() {
  console.log(this.foo);
};

var data = {
  foo: 'bar'
};

var obj = Object.assign(new Project(), data);

obj.print();

Unrelated note It's usually a good idea to declare public functions that don't require closure outside the function body using class.prototype.functionName = function(){...}

  • Related