es6的class类

ES6 提供了更接近传统语

言的写法,引入了 Class(类)这个概念,作为对象的模板。通过class关键字,可以定义类。下面是一个student的类

class Student {
    constructor(name) {
        this.name = name;
    }

    hello() {
        alert('Hello, ' + this.name + '!');
    }
}

class的定义包含了构造函数constructor和定义在原型对象上的函数hello(),比起原来的es5实现方式简洁明了。

创建student实例的方式和原来一样滴

var xiaoming = new Student('小明');
xiaoming.hello();

class继承

class定义对象的另一个巨大的好处是继承更方便了。想一想我们从Student派生一个PrimaryStudent需要编写的代码量。现在,原型继承的中间对象,原型对象的构造函数等等都不需要考虑了,直接通过extends来实现:

class PrimaryStudent extends Student {
    constructor(name, grade) {
        super(name); // 记得用super调用父类的构造方法!
        this.grade = grade;
    }

    myGrade() {
        alert('I am at grade ' + this.grade);
    }
}

PrimaryStudent需要namegrade两个参数,并且需要通过super(name)来调用父类的构造函数,否则父类的name属性无法正常初始化。PrimaryStudent已经自动获得了父类Studenthello方法,我们又在子类中定义了新的myGrade方法

简而言之,用class的好处就是极大地简化了原型链代码。

实际浏览器中运行的时候,就是把class代码转换为传统的prototype代码,那么用Babel这个工具进行转译。

猜你喜欢

转载自blog.csdn.net/weixin_38483133/article/details/88593664