在 ES6 中直接在类上初始化属性是不可能的,目前只能以这种方式声明方法。同样的规则也适用于 ES7。
然而,它是一个提议的特性,可能会在 ES7 之后出现(目前处于第 3 阶段)。这是官方建议。
此外,提案建议的语法略有不同(=
而不是:
):
class Point {
// Declare class property
a = 22
// Declare class static property
static b = 33
}
如果您使用 Babel,您可以使用第 3 阶段的设置来启用此功能。
这是一个 Babel REPL 示例
除了在构造函数中,在 ES6 中执行此操作的另一种方法是在类定义之后执行此操作:
class Point {
// ...
}
// Declare class property
Point.prototype.a = 22;
// Declare class static property
Point.b = 33;
这是一个很好的 SO Thread深入探讨这个主题
注意:
正如Bergi在评论中提到的,建议的语法:
class Point {
// Declare class property
a = 22
}
只是为这段代码提供快捷方式的语法糖:
class Point {
constructor() {
this.a = 22;
}
}
这两个语句都将属性分配给实例。
但是,这与分配给原型并不完全相同:
class Point {
constructor() {
this.a = 22; // this becomes a property directly on the instance
}
}
Point.prototype.b = 33; // this becomes a property on the prototype
两者仍然可以通过实例获得:
var point = new Point();
p.a // 22
p.b // 33
但是获取b
需要在原型链上向上,而a
直接在对象上可用。
