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