Friday, October 7, 2011

Javascript Object Inheritance - Extend and Multiple

These two javascript functions does the inheritance
//inheritance
function extendCopy(obj){
var n = {};
for(var i in obj){
n[i] = obj[i];
}
n.uber = obj;
return n;
}

//multiple inheritance
function multi(){
var n={}, stuff, j=0, len = arguments.length;
for(j=0;j<len;j++){
stuff = arguments[j];
for(var i in stuff){
n[i] = stuff[i];
}
}
return n;
}

Below test the object to see if it worked
//Setting objections
var first_obj = {name:'first', doSomething: function(){alert(2+2);}}
var second_obj = {date:'today', location: 'USA'}
var third_obj = {felling:'happiness', status: 'fun'}
http://www.blogger.com/img/blank.gif
//append/inheritance first first_obj to second_obj
var second_obj = extendCopy(first_obj);
document.write(second_obj.name); // first

//add both the first_obj and third_obj at the same time
var fourth_obj = multi(first_obj,third_obj);
document.write(fourth_obj.felling);// happiness


Another example of javascript inheritance using constructors

No comments:

Post a Comment