组合继承

103 阅读1分钟
也叫伪经典继承
将原型链继承和构造函数继承组合在一块
原型链实现对原型属性和方法的继承
借用构造函数实现对父类属性的继承

 -->
<script>
    function Person() {
        this.foot = 2;
        this.head = 1;
        this.arr = ['前端','大数据']
    }
    Person.prototype.say = function(){
        document.write('脚:'+this.foot + '头:'+ this.head);
    }
    function Student(name) {
        /* 使用call来改变Person的this,父构造函数中的this由Person改成Student */
        // Person.call(this);
        // Person.apply(this);
        Person.bind(this)();
        this.name = name;
    }
    Student.prototype = new Person();
    Student.prototype.constructor = Student;
    let stu1 = new Student('lisi');
    stu1.arr.push('JAVA');
    console.log(stu1.arr);

    /* 子的数据是父给的,但是子不可以改变父的数据 */
    let stu2 = new Student('zhangsan');
    console.log('stu2',stu2.arr);
    // document.write(stu1.foot);
    stu1.say();
</script>