新得关键字class-ES6

ES6中,引入了一个新的关键字class,其目的是让定义类更简单:好处就是极大的简化了原型链的代码

使用函数实现Student的方法:

function Student(name){

this.name = name;

}

Student.prototype.hello = function(){

alert(“hello, ” + this.name  + “!”)

}

如果用新的class关键字来编写Student,可以这样写:

class Student{

 constructor(name){

this.name = name;

}
hello(){

alert(“hello, ” + this.name + “!”)

}

}

相比较以下,class的定义包含了构造函数contructor和定义在原型对象上的函数hello()(注意没有function关键字)这样就避免了Student.prototype.hello = function(){}

class继承

用class定义的另一个巨大的好处是继承更方便:

class PrimaryStudent extends Student{

constructor(name,grade){

super(name);

this.grade = grade;

}

myGrade(){

alert(“I am at grade ” + this.grade );

}

}

注意PrimaryStudent的定义也是class关键字实现的,而extends则表示原型链对象来自Student。子类的构造函数可能与父类不太相同,例如PrimaryStudent需要name和grade两个参数,并且需要通过Super(name)来调用父类的构造函数,否则父类的name属性无法正常的初始化。

但是需要注意的是:不是所有的主流浏览器都支持ES6的class。如果一定要现在就用上米就需要一个工具把 class代码转换成传统的prototype代码,可事实Babel这个工具

posted @ 2018-02-26 13:31  橙子的代码世界  阅读(259)  评论(0编辑  收藏  举报