Javascript inheritance using prototype, what is the practical way?

I was reading about inheritance in Javascript and came up with creating constructors and defining each constructor prototype. I created a function prototypeExtend

that will loop through each constructor prototype and add it to the main constructor prototypes.

Is this a practical way to achieve inheritance?

function prototypeExtend() {
    var cMain = arguments[0].prototype;
    for(var i=1; i<arguments.length; i++){
        var cTemp = arguments[i].prototype;
        for(var k in cTemp){
            if(cTemp.hasOwnProperty(k)){
                cMain[k] = cTemp[k];
            }
        }
    }
    return cMain;
}

function Class1 () {}
Class1.prototype = {
        el1:null,
        fun1:function(str){
            console.log(str + " from Class1");
        },
        setEl1:function(value){
            this.el1 = value;
        },
        getEl1:function(){
            return this.el1;
        }
}

function Class2(){}
Class2.prototype = {
        el2:"blah",
        fun2:function(str){
            console.log(str + " from Class2");
        }
}

function Class3(){}
Class3.prototype = {
        el3:"dah",
        fun3:function(str){
            console.log(str + " from Class3");
        },
        fun1:function(str){
            console.log(str + " from Class3");
        }
}
prototypeExtend(Class2, Class1, Class3);
var obj = new Class2;
console.log(obj);

      

+3


source to share


2 answers


In this state, I can think of something that you may not have seen. You give default values ​​for object properties directly in the prototype description. Remember that objects (and functions) will be passed by reference, so these properties will be static if I can reference Java. Any change to the object will affect all other links.

You will also have to change your code when you need to override functions and use the parent.



If your goal is to build your own library then keep that in mind and keep going!;) Anyway, you should take a look at what others are doing on the internet. I have personally used classjs and it did the job for me!

+1


source


Here are some good examples of prototype and functional inheritance

http://artandlogic.com/2012/07/prototypal-vs-functional-inheritance-in-javascript/

This seems to be a very opinion-based question, so there is nothing wrong or wrong. I personally love the prototype approach.



EDIT1: Also check out Douglas Crockford - he has his own implementation and is a javascript guru that many people follow

http://javascript.crockford.com/prototypal.html

I hope this has pointed you in the right direction

0


source







All Articles