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

161
Visualizações
`Object.create(Vec2.prototype)` lacks class properties

I would like to instantiate classes without calling new by using Object.create (which is made for it), but how can I get all properties defined aswell?

class Vec2 {
  x = 0;
  y = 0;
}
a = new Vec2;
b = Object.create(Vec2.prototype);

console.log(a.x, a.y);
console.log(b.x, b.y);

a.x and a.y exist, but b.x and b.y do not.

Appendum for Bergi comments:

[1]

function Vec1() {
  this.x = 0;
}
b = Object.create(Vec1.prototype);
Vec1.apply(b);

[2]

class Vec3 {
  x = console.log("x = ...");
  constructor() {
    console.log("constructor");
  }
  y = console.log("y = ...");
}
vec3 = new Vec3;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I would like to instantiate classes without calling new by using Object.create (which is made for it)

No, that's not what Object.create is made for. Its purpose is to create objects with a custom prototype object - a very useful low-level functionality.

To instantiate a class, and in particular to run its constructor code, you must use new, there's no way around it.

Of course you can ignore to do that, and just create your own objects with the same prototype chain, nothing to stop you there:

class Vec2 {
  x = 0;
  y = 0;
  print() {
    console.log(`(${this.x}, ${this.y})`);
  }
}
const a = new Vec2();
a.print(); // (0, 0)
const b = Object.create(Vec2.prototype);
b.x = 1;
b.y = 1;
b.z = 1;
b.print(); // (1, 1)

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