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
需要name
和grade
两个参数,并且需要通过super(name)
来调用父类的构造函数,否则父类的name
属性无法正常初始化。PrimaryStudent
已经自动获得了父类Student
的hello
方法,我们又在子类中定义了新的myGrade
方法
简而言之,用class
的好处就是极大地简化了原型链代码。
实际浏览器中运行的时候,就是把class
代码转换为传统的prototype
代码,那么用Babel这个工具进行转译。