与C++
中的Class
类似。但是不存在私有成员。
定义
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| 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 10
| 1class 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 14 15 16 17 18
| class Point { constructor(x, y) { this.x = x; this.y = y; }
toString() { return "(" + this.x + ", " + this.y + ")"; }
static print_class_name() { console.log("Point"); } }
let p = new Point(1, 2); Point.print_class_name(); p.print_class_name();
|
静态变量
在 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);
|


xujiaojiao
生活明朗,万物可爱
此文章版权归xujiaojiao所有,如有转载,请注明来自原作者