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

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

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 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