ES6 - class 类

134 阅读1分钟

实例

class Animal {  //用class定义了一个“类”
    constructor(){   //constructor构造方法
        this.type = 'animal'  //this关键字代表实例对象
    }
    says(say){
        console.log(this.type + ' says ' + say)
    }
}

let animal = new Animal()
animal.says('hello') //animal says hello

class Cat extends Animal { 
//Class之间可以通过extends关键字实现继承,通过extends关键字,继承了Animal类的所有属性和方法
    constructor(){
        super()  //super关键字,它指代父类的实例(即父类的this对象)
        this.type = 'cat'  //子类没有自己的this对象,而是通过super继承父类的this对象
    }
}

let cat = new Cat()
cat.says('hello') //cat says hello

总结

  • class定义了一个“类”

  • 类里面有一个constructor方法,这就是构造方法,而this关键字则代表实例对象。

  • Class之间可以通过extends关键字实现继承

  • super关键字,它指代父类的实例(即父类的this对象)。子类必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。如果不调用super方法,子类就得不到this对象。