深入浅出javascript(十二)继承——构造函数继承和组合继承

#题记:

有一水果类,抽象出属性包括:name(水果品种),price(价格),id(ID号)。现有两个子类,分别为苹果,桔子,希望继承水果父类。

一、构造函数继承

构造函数继承相当把父类的属性在子类执行一遍(可以理解为复制一遍),代码如下:

        //父类:水果类
        function Fruit(name, price, id) {
            this.name = name;
            this.price = price;
            this.id = id;
        }
        //苹果类
        function Apple(name, price, id) {
            Fruit.call(this, name, price, id);  //执行一遍父类的属性
        }
        //桔子类
        function Orange(name, price, id) {
            Fruit.call(this, name, price, id);  //执行一遍父类的属性
        }
        var apple = new Apple('苹果', '10.5', '001');     //实例苹果,可以传参了
        var orange = new Orange('桔子', '8.5', '002');    //实例桔子,可以传参了
        console.log(apple.name);
        console.log(orange.price);

二、构造函数解决的优点和缺点

一、优点

构造函数解决了原型继承中不能向父类传参的问题,它能灵活的向父类传送参数。并且继承的属性完全属于自己,不会和其它的子类产生影响。示例图:

二、缺点

构造函数继承不能继承父类的原型方法,参照这些条件,自然想到可以将它们组合一起。

三、组合继承

组合继承即是把原型继承构造函数继承组合一起。

示例代码如下

        //父类:水果类
        function Fruit(name, price, id) {
            this.name = name;
            this.price = price;
            this.id = id;
        }
        Fruit.prototype.getInfo=function()
        {
            console.log(this.name + ',' + this.price + ',' + this.id);
        }
        //苹果类
        function Apple(name, price, id) {
            Fruit.call(this, name, price, id);  //执行一遍父类的属性
        }
        //桔子类
        function Orange(name, price, id) {
            Fruit.call(this, name, price, id);  //执行一遍父类的属性
        }
        Apple.prototype = new Fruit();          //继承了父类的原型方法
        Orange.prototype = new Fruit();         //继承了父类的原型方法

        var apple = new Apple('苹果', '10.5', '001');     //实例苹果,传参
        var orange = new Orange('桔子', '8.5', '002');    //实例桔子,传参
        apple.getInfo();        //输出'苹果', '10.5', '001'
        orange.getInfo();       //输出'桔子', '8.5', '002'

一、组合继承的优点和缺点

优点是:几乎很完美了,既能独立继承父类的属性,也能继承父类的原型方法。

缺点是:父类的构造函数执行了两遍,一次在call调用时,一次在原型继承时。

原文地址:https://www.cnblogs.com/tinaluo/p/8707927.html