js中继承的实现

image.png


function People(name,age,sex){
    this.name = name;
    this.age = age;
    this.sex = sex;
}
People.prototype.changge = function(){
    console.log(`我是一个${this.name},我今年${this.age}岁了`);
}


function Student(name,age,sex,xuehao,banji){
    this.name = name;
    this.age = age;
    this.sex = sex;
    this.xuehao = xuehao;
    this.banji = banji;
}
Student.prototype = new People();
Student.prototype.kaoshi = function(){
    console.log(`${this.name}在考试`);
}

var xiaohua = new Student("小花",12,"女",10001,"1班");
xiaohua.changge(); //原型链查找
xiaohua.kaoshi(); 

image.png

ES6中简化了类的继承


class People{
    constructor(name , age , sex){
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    changge(){
        console.log("我是一个" + this.name + "今年" + this.age + "岁啦!!");
    }

    goDie(){
        console.log("死啦");
    }
}

class Student extends People{
    constructor(name , age , sex , xuehao , banji){
        super(name , age , sex);     //调用超类的构造器
        this.xuehao = xuehao;
        this.banji = banji;
    }

    kaoshi(){
        console.log(`${this.name}在考试`);
    }
}

var xiaohua = new Student("小花",12,"女",10001,"1班");
xiaohua.changge();
xiaohua.kaoshi();

image.png
super():父类的构造函数


素素
37 声望0 粉丝