Cis*_*nas 15 javascript ecmascript-6
了解如何在构造函数中声明x和y:
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法在函数之外声明属性,例如:
class Point {
// Declare static class property here
// a: 22
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
Run Code Online (Sandbox Code Playgroud)
所以我想分配给22,但我不确定我是否可以在构造函数之外做但仍然在类中.
nem*_*035 28
直接在ES6中的类上初始化属性是不可能的,目前只能以这种方式声明方法.同样的规则也适用于ES7.
但是,这是一个建议的功能,可能会在ES7之后(目前处于第3阶段).这是官方提案.
此外,提案建议的语法略有不同(=而不是:):
class Point {
// Declare class property
a = 22
// Declare class static property
static b = 33
}
Run Code Online (Sandbox Code Playgroud)
如果您使用的是Babel,则可以使用第3阶段设置启用此功能.
除了构造函数之外,在ES6中执行此操作的另一种方法是在类定义之后执行此操作:
class Point {
// ...
}
// Declare class property
Point.prototype.a = 22;
// Declare class static property
Point.b = 33;
Run Code Online (Sandbox Code Playgroud)
这是一个很好的SO线程潜入这个主题更多
注意:
正如Bergi在评论中提到的,建议的语法:
class Point {
// Declare class property
a = 22
}
Run Code Online (Sandbox Code Playgroud)
只是语法糖为这段代码提供快捷方式:
class Point {
constructor() {
this.a = 22;
}
}
Run Code Online (Sandbox Code Playgroud)
这两个语句都将属性分配给实例.
但是,这与分配原型不完全相同:
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
Run Code Online (Sandbox Code Playgroud)
两者仍然可以通过实例获得:
var point = new Point();
p.a // 22
p.b // 33
Run Code Online (Sandbox Code Playgroud)
但是,直接可以在对象b上获得原型链a.