是否可以在js类关键字中声明原型属性


class A {
// Will be declared on the class instance
name = “one”;
// Will be declared on the class constructor 
static otherName = “two”;
// Will be on the prototype
// Is this also possible for properties? (not just for methods)
greet() {}
}

有可能用这种语法在类的原型上声明一个属性吗?

谢谢。

不,这不是任何字段建议的一部分。您需要使用Object.defineProperty单独创建它们。

Object.defineProperty(A.prototype, 'name', {
value: 'one',
configurable: true,
});

您可以定义一个getter。

class A {
get x(){
return 1;
}
}
console.log(A.prototype.x);

最新更新