es6 之 class(二) 继承

基本用法

  1. class通过extends关键字来实现继承,es5通过修改原型链实现继承

  2. es6的子类this是基于父类this进行修改的,es5是先创造子类this,然后将父类的方法添加到子类this上

    1. 子类必须在构造函数中调用super方法(创建父类实例),否则创建实例会失败
    2. 子类只有调用完super方法后,才能使用this关键字
    3. 在子类中,super关键字代表父类实例(即父类的this)

    3.可以通过Object.getPrototypeOf(childClass) === parentClass来判断继承关系

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    class A{

    }

    class B extends A{
    constructor(x){
    super();
    this.x = x;

    }
    }

    let b=new B();

    原生构造函数的继承

    原生构造函数指的是js原生对象的构造函数,如String()、Number()、Array()、Object()等。

    es5是新建子类后,再将父类的属性添加到子类上,而父类的属性无法获取到,导致无法继承自动父类的内部属性。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    function MyArray(){
    Array.apply(this, arguments);
    }

    MyArray.prototype = Object.create(Array.prototype,{
    constructor:{
    value:MyArray,
    writable:true,
    configurable:true,
    enumberable:true
    }
    });

    let arr = new MyArray();
    arr[0] = 'fff';
    console.log('arr.length:\n',arr.length);//输出为0