Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

157
Views
Construct an object that has member functions from an object that has no member function with their properties are the same?

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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(){...}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!