在ES6中,class之间可以通过extends进行继承:
我们先定义一个父类 Point:
1 class Point{ 2 constructor(color){ 3 this.color=color; 4 } 5 6 }
之后再定义一个子类,让子类Test继承父类Point
1class Test extends Point{ 2 constructor(color,name,age){ 3 super(color); //调用父类的constructor(color); 4 this.name=name; 5 this.age=age; 6 } 7 Who(){ 8 alert(this.color); 9 } 10 } 11 12 var ND=new Test("red","ND",25); 13 14 ND.Who() //alert出 red
Test类通过extends关键字继承了,Point类里的所有方法和属性;
super关键字,的作用是表示父类的构造函数,用来新建父类的this对象,必须在子类的constructor中调用super方法,因为子类没有自己的this对象,而是继承的父类的this对象,让后对其加工,如果不调用super,子类就得不到this对象;