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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值