组合继承

116 阅读1分钟

/* 也叫伪经典继承 将原型链继承和构造函数继承组合在一块 原型链 实现对 原型属性和方法 的继承 借用 构造函数 实现对 实例属性 的继承 */

    function Person() {
        // 实例属性
        this.head = 1;
        this.foot = 2;
    }
    // 原型属性和方法
    Person.prototype.weight = '70kg';
    Person.prototype.eat = function () {
        console.log('我会吃');
    }
    function Student() {
        // 借用构造函数对 实例属性进行继承
        Person.call(this)
    }
    // 借用原型链对原型属性和方法继承
    Student.prototype = new Person()
    Student.prototype.constructor = Student
    let stu1 = new Student();
    console.log(stu1);
    stu1.eat()



    function Car() {
        this.lunzi = 4

    }
    Car.prototype.run = function () {
        console.log((`${this.name}${this.lunzi}个轮子,会跑赛道`));
    }
    function Bc(name) {
        Car.call(this)
        this.name = name;
    }
    Bc.prototype = new Car()
    Bc.prototype.constructor = Bc

    let bc1 = new Bc('奔驰')
    console.log(bc1);
    bc1.run()