Skip to content

Latest commit

 

History

History
46 lines (37 loc) · 751 Bytes

15.1.md

File metadata and controls

46 lines (37 loc) · 751 Bytes

15.1 概览

类和子类:

class Point {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
    toString() {
        return `(${this.x}, ${this.y})`;
    }
}

class ColorPoint extends Point {
    constructor(x, y, color) {
        super(x, y);
        this.color = color;
    }
    toString() {
        return super.toString() + ' in ' + this.color;
    }
}

在背后, ES6 类不是一个全新的东西:主要提供了更多方便的语法去创建老式的构造器函数。如果使用 typeof 可以看到:

> typeof Point
'function'

使用类:

> let cp = new ColorPoint(25, 8, 'green');

> cp.toString();
'(25, 8) in green'

> cp instanceof ColorPoint
true
> cp instanceof Point
true