`Object.create(Vec2.prototype)` lacks class properties

44 views Asked by At

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

There are 1 answers

5
Bergi On

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)