ES6--类继承

102 阅读2分钟

这是我参与11月更文挑战的第15天,活动详情查看:2021最后一次更文挑战

前言

ECMAScript6新增特性中最出色的个就是原生支持了类继承机制。虽然类继承使用的是新语法,但背后依旧使用的是原型链。我们今天来讲一讲ES6的类继承。

继承基础

ES6类支持单继承。使用 extends 关键字,就可以继承任何拥有 Construct 函数和原型的对象。 很大程度上,这意味着不仅可以继承一个类,也可以继承普通的构造函数(保持向后兼容):

 class Vehicle {}
//继承类

 claSs Bus extends Vehicle {
 let b = neW Bus () 
 Console .1og( binstanceofBuS );
 console , log ( binstanceof Vehicle );
}
//继承普通构造函数
 claSs Engineer extends Person (} (
 
1et neWEngineer ();
 console . log ( e instanceof Engineer );// true 
 console . log ( einstanceof Person ); // true 

类和原型上定义的方法都会带到派生类。 this 的值会反映调用相应方法的实例或者类: 

class Vehicle (
 ident ifyPrototype ( id )(
 console . log ( id , this );

stat ic identifyClass ( id )
 console . log ( id , this );

 class Bus extends Vehicle {
 let V = new Vehicle (); 
 iet b = neW Bus (); 
 b . identifyPrototype (' buS '); 
 V . identifyPrototype (' vehicle ');
 Bus . identifyClass (' bus ');
 Vehicle . identifyClass (' vehicle ');}

注意 extends 关键字也可以在类表达式中使用,因此 let Bar = class extends Foo 0
是有效的语法。

构造函数、 HomeObject 和super ()

派生类的方法可以通过 super 关键字引用它们的原型。这个关键字只能在派生类中使用,而且仅 a 千类构造函数、实例方法和静态方法内部。在类构造函数中使用 super 可以调用父类构造函数。

class Vehicle ( constructor ()(
 this . hasEng ine = true ;

 class Bus extends Vehicle { constructor (){
//不要在调用 super ()之前引用 this ,否则会抛出 ReferenceError 
 super ();//相当于 super . constructor ()
 console . log ( this instanceof Vehicle );// true 
 console . log ( this ); // Bus { hasEngine : true }

 new Bus ();

在静态方法中可以通过 super 调用继承的类上定义的静态方法: class Vehicle (\

 static í dentify ()(
 console . log (' vehicle ');
 class Bus extends Vehicle ( static identify ()(
 super.dentify ();

 Bus.dentify ();// vehicle

抽象基类

候可能需要定义这样一个类,它可供其他类继承,但本身不会被实例化。虽然 ECMAScript 没古持这种类的语法,但遇过 new . target 也很容易实现。 new . target 保存通过 new 关键字调 h 米忒函数。通过在头例化时检测 new . target 是不是抽象基类,可以阻止对抽象基类的实例化:

//抽象基类
 class Vehicle { constructor (){
 console . log ( new . target );
 if ( new . target === Vehicle ){
 throW new Error (' Vehicle cannot be directly instantiated ');
 

继承内置类型

ES6类为继承内置引用类型提供了顺畅的机制,开发者可以方便地扩展内置类型:

 claSSSuperArray extends Array {
 shuffle (){
//洗牌算法
 for ( let i = this . length -1; i >0; i --){ 
 const j = Math . floor ( Math . random ()*( i +1));
[ this [ i ], this [ j ]]=[ this [ j ], this [ i ]];
1et a = new SuperArray (1,2,3,4,5);
 console . lOg ( ainstanceof Array ); // true 
 console . log ( a instanceof SuperArray );// true