K3NN3TH
K3NN3TH

Reputation: 1496

Javascript inheritance using prototype, what is a practical way?

I've been reading up on inheritance in Javascript and have come up with creating constructors and defining each constructors prototypes. I've created a prototypeExtend function that will loop through each constructors prototypes and add them to the main constructors 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);

Upvotes: 3

Views: 89

Answers (2)

Robin Nicolet
Robin Nicolet

Reputation: 264

In this state, I can think of something that you might not have see. You're giving default values to your objects's properties directly in the prototype description. Remember that objects (and functions) will be passed by reference thus these properties will be static, if I can refer to Java. Any change to the object will impact every other references.

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

If your goal is to develop your own library then keep that in mind and go on ! ;) In any way, you should take a look at what others do on the web. I've personally been using classjs and it did the job for me !

Upvotes: 1

Max Bumaye
Max Bumaye

Reputation: 1009

Here are nice examples of prototypal vs functional inherritance

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

It seems to be a very opinion based question so there is no wrong or right. I personaly like the prototypal approach alot.

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

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

I hope this pointed you in the right direction

Upvotes: 0

Related Questions