Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

150
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda