' Object.create(Vec2.prototype) '缺少类属性



我想通过使用Object.create(这是为它做的)来实例化类而不调用new,但是我怎么能得到定义的所有属性呢?

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.xa.y,不存在b.xb.y

Bergi注释附录:

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

我想通过使用Object.create(这是为它制作的)来实例化类而不调用new

不,那是而不是Object.create是用来做什么的。它的目的是用自定义原型对象创建对象——一个非常有用的底层功能。

要实例化class,特别是运行它的构造函数代码,必须使用new

当然,你可以忽略这一点,只是用相同的原型链创建你自己的对象,没有什么可以阻止你:

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)

最新更新