JavaScript继承-借用构造函数继承

借用构造函数继承是在子类型构造函数的内部调用超类型狗在函数,通过使用apply()和call()方法

    function girlFriend(){
        this.girls = ['chen','wang','zhu'];
    }
    function Person(){
        girlFriend.call(this,20);
    }
    var wang = new Person();
    var zhu = new Person();
    wang.girls.push('zhang');
    console.log(wang.girls);    //(4) ["chen", "wang", "zhu", "zhang"]
    console.log(zhu.girls);        //(3) ["chen", "wang", "zhu"]

通过以上代码,我们可以发现,在原型链继承中出现的问题不再出现了,这个超类不会被子类所创建的实例共享了。

借用构造函数继承的优势是可以在子类型构造函数中向超类型构造函数传递参数,例如以下代码:

    function SuperType(name){
        this.name = name;
    }
    function SubType(){
        SuperType.call(this,"nick");
        this.age = 20;
    }
    var instance = new SubType();
    console.log(instance.name);        //nick
    console.log(instance.age);        //20

猜你喜欢

转载自www.cnblogs.com/gehaoyu/p/11804384.html