How to do multiple inheritance in javascript

Asked

Viewed 551 times

4

I’ve seen a lot of ways to do it inheritance in javascript, but do not know how to do inheritance-multiple I will demonstrate an example of the problem:

        function Transporte() { 
            var nome; 
            this.getNome = function () { 
                return nome; 
            }; 
            this.setNome = function (value) { 
                nome = value; 
            }; 
        } 

        function Motor() { 
            var motor; 
            this.getMotor = function () { return motor; }; 
            this.setMotor = function (value) { motor = value; }; 
        } 

        function Propulsor() { 
            var propulsor; 
            this.getTurbina = function () { return propulsor; }; 
            this.setTurbina = function (value) { propulsor = value; }; 
        } 

        Motor.prototype = new Transporte(); 
        Propulsor.prototype = new Transporte();

        function document_OnLoad() { 
            var carro = new Motor(); 
            var aviao = new Propulsor(); 

            carro.setMotor('4.1');
            carro.setNome('opala');

            aviao.setTurbina('123');
            aviao.setNome('Teco-Teco');

            console.log(carro.getMotor()+'  '+carro.getNome());
            console.log(aviao.getTurbina()+'  '+aviao.getNome());
        }

In this way that the source code was written, I have a simple inheritance:

  • Car Motor Instance and Inherited Transport
  • Aircraft Propulsion Instance and inherited from Transport

My question is:

Use the prototype to inherit Engine, Propeller and Transport?

It has to use some feature to inherit Motor, Propeller and Transport?

  • 2

    I suggest taking a look at the concept of mixins, because Javascript does not support multiple inheritance directly (i.e. a prototype chain forms a simple tree, in which each object has only a single prototype, can no longer have). P.S. More information on the operation of prototypes and inheritance javascript.

1 answer

1


I found a technique that solves the question I will post the library and give the credit to Mr. Nicholas C. Zakas who made the code available on his page.

http://www.nczonline.net/downloads/zInherit1.0.zip

I will exemplify your use as below:

	/*------------------------------------------------------------------------------
	 * JavaScript zInherit Library
	 * Version 1.0
	 * by Nicholas C. Zakas, http://www.nczonline.net/
	 * Copyright (c) 2004-2005 Nicholas C. Zakas. All Rights Reserved.
	 *
	 * This program is free software; you can redistribute it and/or modify
	 * it under the terms of the GNU Lesser General Public License as published by
	 * the Free Software Foundation; either version 2.1 of the License, or
	 * (at your option) any later version.
	 *
	 * This program is distributed in the hope that it will be useful,
	 * but WITHOUT ANY WARRANTY; without even the implied warranty of
	 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	 * GNU Lesser General Public License for more details.
	 *
	 * You should have received a copy of the GNU Lesser General Public License
	 * along with this program; if not, write to the Free Software
	 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
	 *------------------------------------------------------------------------------
	 */
	 
	/**
	 * Inherits properties and methods from the given class.
	 * @scope public
	 * @param fnClass The constructor function to inherit from.
	 */
	Object.prototype.inheritFrom = function (fnClass /*: Function */) /*:void*/ {

		/**
		 * Inherits all classes going up the inheritance chain recursively.
		 * @param fnClass The class to inherit from.
		 * @param arrClasses The array of classes to build up.
		 * @scope private
		 */
		function inheritClasses(fnClass /*:Function*/, 
								arrClasses /*:Array*/) /*:void*/ {
			
			arrClasses.push(fnClass);

			if (typeof fnClass.__superclasses__ == "object") {
				for (var i=0; i < fnClass.__superclasses__.length; i++){
					inheritClasses(fnClass.__superclasses__[i], arrClasses);
				}
			}
		}
		
		if (typeof this.constructor.__superclasses__ == "undefined") {
			this.constructor.__superclasses__ = new Array();
		}
		
		inheritClasses(fnClass, this.constructor.__superclasses__);
		
		for (prop in fnClass.prototype) {
			if (typeof fnClass.prototype[prop] == "function") {
				this[prop] = fnClass.prototype[prop];
			}
		}
	};

	/**
	 * Determines if the given object is an instance of a given class.
	 * This method is necessary because using {@link #inheritFrom} renders
	 * the JavaScript <code>instanceof</code> operator useless.
	 * @param fnClass The constructor function to test.
	 * @return True if the object is an instance of the class, false if not.
	 * @scope public
	 */
	Object.prototype.instanceOf = function (fnClass /*:Function*/) /*: boolean */ {

		if (this.constructor == fnClass) {
			return true;
		} else if (typeof this.constructor.__superclasses__ == "object") {
			for (var i=0; i < this.constructor.__superclasses__.length; i++) {
				if (this.constructor.__superclasses__[i] == fnClass) {
					return true;
				}
			}
			return false;
		} else {
			return false;
		}
	};

function Transporte() { 
           var nome; 
           this.getNome = function () { return nome; }; 
           this.setNome = function (value) { nome = value; };             
    } 

    function Motor() { 
        var motor; 
        this.getMotor = function () { return motor; }; 
        this.setMotor = function (value) { motor = value; }; 
    } 

    function Propulsor() { 
        var propulsor; 
        this.getTurbina = function () { return propulsor; }; 
        this.setTurbina = function (value) { propulsor = value; }; 
    } 

    function CarroVoador(){
        Motor.apply(this);
        Propulsor.apply(this);
        Transporte.apply(this);
    }

    Motor.prototype = new Transporte(); 
    Propulsor.prototype = new Transporte();

    CarroVoador.prototype.inheritFrom(Motor);
    CarroVoador.prototype.inheritFrom(Propulsor);
    CarroVoador.prototype.inheritFrom(Transporte);

    var carro = new Motor(); 
    var aviao = new Propulsor(); 
    var carroVoador = new CarroVoador();
    carro.setMotor('4.1');
    carro.setNome('opala');

    aviao.setTurbina('123');
    aviao.setNome('Teco-Teco');

    carroVoador.setNome('supercarro');
    carroVoador.setTurbina('123');
    carroVoador.setMotor('4.1');

    $('body').append('motor: '+carro.getMotor()+' nome:'+carro.getNome());
    $('body').append('<br/>').append('propulsor: '+aviao.getTurbina()+' nome: '+aviao.getNome());
    $('body').append('<br/>').append('motor: '+carroVoador.getMotor()+' propulsor: '+carroVoador.getTurbina()+' nome: '+carroVoador.getNome());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.