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);
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 !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With