ES6 中的Class中的关键字super

发布时间:2019-08-13 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了ES6 中的Class中的关键字super脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

复习一下ES6 中的关于类的语法

定义一个类

class Animal {
    constructor(){
        this.tyPE = 'animal';
    }
    speak(){
        console.LOG(this.type);
    }
}

相当于下面ES5的这样的写法

function Animal(){
   this.type = 'animal';
}

Animal.PRototype.speak = function(){
   console.log(this.type);
}

类的继承

class Animal {
    constructor(){
        this.type = 'animal';
    }
    speak(){
        console.log(this.type);
    }
}

class Cat extends Animal {
    constructor(){
        super();
        this.type = 'cat'
    }
}

相当于下面ES5的写法

function Animal(){
   this.type = 'animal';
}

Animal.prototype.speak = function(){
   console.log(this.type);
}

function Cat(){
  Animal.call(this);
  this.type = 'animal';
}
Cat.prototype = Object.create(Animal.prototype);
Cat.prototype.constructor = Cat;//因为上一步造成constructor为Animal

//或者可以把上边的两行改成下面这样的写法
Cat.prototype = Object.create(Animal.prototype, {
  constructor: Cat,
});

super登场

从上边的例子可能已经领略了super的一些用法了。但是还不全面。super在类的继承中,有两个用法

  1. 作为函数使用,如上边的例子中的super()
  2. 作为对象使用, 如super.type

1. 把super作为函数使用

在类的继承中,子类如果显式的声明了构造函数,则必须首先调用super,不然会找不到this。此时super代表父类的构造函数。这时在构造函数里调用super(),相当于 parentConstructor.call(this). 还是以上边的实际例子为例

class Cat extends Animal {
    constructor(){
        super();   // 相当于  Animal.call(this)
        this.type = 'cat'
    }
}

现在再解释一个疑问。如果在继承中子类压根不写构造函数呢?不过不写,相当于也写了。只是构造函数用的是父类的构造函数

class Cat extends Animal {
}

// 相当于
class Cat extends Animal {
    constructor(...args){
             super(...args);
    }
}

2.把super作为对象使用

super作为对象时,在普通方法中,指向父类的原型对象;在静态方法中,指向父类。

在普通方法中,指向父类的原型对象,下面举例

class Animal {
    constructor(){
        this.type = 'animal';
    }
}

Animal.prototype.type ="type on propotype"

class Cat extends Animal {
    constructor(){
        super();
        this.type = 'cat'
               console.log(super.type)
    }
}
new Cat();  // 此处打印出来的是type on propotype,而不是animal

在静态方法中指向父类

class Animal {
  static type = 'this is static type';
    constructor(){
        this.type = 'animal';
    }
}

Animal.prototype.type ="type on propotype"

class Cat extends Animal {
    constructor(){
        super();
        this.type = 'cat'
    }
  static miao(){
    console.log(super.type);  // 这里输出的是this is static type,而不是animal或者type on propotype
  }
}

Cat.miao()

脚本宝典总结

以上是脚本宝典为你收集整理的ES6 中的Class中的关键字super全部内容,希望文章能够帮你解决ES6 中的Class中的关键字super所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。