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

  • this 指向类的实例。

定义

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

继承

class ColorPoint extends Point {
    constructor(x, y, color) {
        super(x, y); // 这里的 super 表示父类的构造函数
        this.color = color;
    }

    toString() {
        return this.color + ' ' + super.toString(); // 调用父类的 toString()
    }
}

WARNING

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

静态方法

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

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 定义和访问。例如:

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