定义

与C++中的Class类似。但是不存在私有成员。

this指向类的实例。
定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Point {
constructor(x, y) { // 构造函数
this.x = x; // 成员变量
this.y = y;
this.init();
}

init() {
this.sum = this.x + this.y; // 成员变量可以在任意的成员函数中定义
}

toString() { // 成员函数
return '(' + this.x + ', ' + this.y + ')';
}
}

let p = new Point(3, 4);
console.log(p.toString());

继承

1
2
3
4
5
6
7
8
9
class ColorPoint extends Point {
constructor(x, y, color) {
super(x, y);
this.color = color;
}
toString() {
return `(${this.color}${super.toString()})`
}
}

注意:
super这个关键字,既可以当作函数使用,也可以当作对象使用。
作为函数调用时,代表父类的构造函数,且只能用在子类的构造函数之中。
super作为对象时,指向父类的原型对象。
在子类的构造函数中,只有调用super之后,才可以使用this关键字。
成员重名时,子类的成员会覆盖父类的成员。类似于C++中的多态。

静态方法

在成员函数前添加static关键字即可。静态方法不会被类的实例继承,只能通过类来调用。例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}

toString() {
return `(${this.x},${this.y})`;
}
static print_class_name() {
console.log("Point");
}
}

静态变量

在ES6中,只能通过class.propname定义和访问。例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Point {
constructor(x, y) {
this.x = x;
this.y = y;

Point.cnt++;
}

toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}

Point.cnt = 0;

let p = new Point(1, 2);
let q = new Point(3, 4);

console.log(Point.cnt);