js,构造器继承和class继承

127 阅读1分钟
function dog(){
    this.dogSay = ()=>console.log("旺旺");
}
function people(){
    this.peopleSay = ()=>console.log("不要叫");
}
//把狗的叫声给人身上
people.prototype = new dog()
//new 一个叫superMan接受一下这个人的
let superMan = new people()
//superMan学狗叫
superMan.dogSay()  //旺旺
//superMan学人叫
superMan.peopleSay()  //不要叫

// class类的继承
class dog{
    constructor(num){
        this.num = num
    }
    dogSay(){
        console.log(`学狗叫,叫了${this.num}声`);
    }
}
class people extends dog{
    //第一种
    constructor(i){   
        super(i =3)   // i 实际上是dog里面constructor里面的num,即参数
    }
    //第二种
    constructor(){   
        super(3)   // 直接默认赋值
    }
    peopleSay(){
        console.log(`说了${this.num}声,不要叫了。`);
    }
}
let superMan = new people()
superMan.dogSay()
superMan.peopleSay()

image.png