ES6 - 类的继承

在es6的继承中,我们使用extends关键字。

 //定义父类
class Person{
    constructor(name="xf",age){
        this.name = name;
        this.age = age;     
    }
    say(){
        console.log("nice to meet you " + this.name);
    }
}
//定义子类并继承父类
class Child extends  Person{
    //如果子类没有写constructor构造函数,那么默认有个空的构造函数constructor
    constructor (name="winne",age=20,height=10){
        //如果子类写了构造函数,那么调用super()函数时必须在构造函数的第一句调用,不然在其之前调用this会报错
        //如果子类的某些参数想要覆盖父类的那些参数,那么在调用super()的时候传入
        super(name,age);
        this.height = height;
        this.type = "child";
    }
}

let child1 = new Child();
console.log(child1); // Child {name: "winne", age: 20, height: 10, type: "child"}
child1.say(); // nice to meet you winne

1、子类没用定义constrcutor构造函数时,默认会添加 一个,并且默认的调用了super()函数。
2、子类定义了constructor构造函数时,必须显示的在构造函数中调用super()函数,然后才能使用this来获取继承来的或者自身的属性和方法。

猜你喜欢

转载自blog.csdn.net/m0_38134431/article/details/84315755