Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

151
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda