ES2015 类 class 语法

在ES2015之前,定义类的方法只能通过原型链来模拟

function Animal(family,species) {
    this.family = family;
    this.species = species;
};
Animal.prototype.yell = function() {
    console.log(this.family);
}
let dog = Animal('dogs','four feet');

而在ES2015中可以使用class关键字来定义类,使用constructor来定义类创建时所需的参数,直接定义函数来创建类方法:

class Animal {
    constructor (family,species) {
        this.family = family;
        this.species = species;
    };
    yell () {// 等于Animal.prototype.yell = function(){}
        return this.family;
    }
}

const dog = new Animal('dog','four feet');

在类定义中可以看到yell的方法没有使用键值对的方式,这也是ES6中新引入的对象字面量扩展,等同于:

const Animal= {
    yell: function() {
        return this.family;
    }
}

类 + promise

class Point {
    constructor (x, y) {
        this.x = x;
        this.y = y;
    };
    moveright(step) {
        return new Promise(resolve => resolve({
            x: this.x + step,
            y: this.y
        }))
    }
}
const p = new Point(2,5);

定义一个点类,拥有moveright的方法,返回的使一个Promise,利用箭头函数调用resolve,使Promise状态转换到onFulfilled。

p.moveright(3)
.then(({x, y}) => console.log(`${x}, ${y}`));//5,5

这里的{x,y} 用了ES6的新语法解构,将返回的对象中的x和y键对应的值返回。

下面讲讲类的继承,在函数中的继承有很多种继承方式,具体的继承方式我会在我的博客中更新。

创建一个Point2D类

class Point2D {
    constructor(x,y) {
        this.x = x;
        this.y = y;
    }
    toString() {
        console.log('2d function');
        return `${this.x},${this.y}`;
    }
};

创建Point3D类并继承Point2D,核心关键字extends, super

class Point3D extends Point2D {
    constructor(x,y,z) {
        super(x,y);// 如果没有super,则在constructor中不能使用this,其他方法中可以。
        this.z = z;
    }
    toString(){
        super.toString();
        return `${this.x},${this.y},${this.z}`;
    }
};

这样的继承方式比使用function继承来的更为直接和方便。

最后测试:

const p = new Point3D(1,2,3)
p.toString()

输出为:

这样使用super便实现了对父类方法的继承。

原文地址:https://www.cnblogs.com/BigJ/p/class.html