I have wrote a utility module for Object Inheritance in JavaScript
Here is the Full Source Code.
(function(){
window.MUI=window.MUI || {};
MUI.object=MUI.object ||
{
is:function(){
if(arguments.length<1)
throw "This function need at least one parameter.";
var b=true;
for(var i=0,len=arguments.length;i<len;i++){
if(typeof arguments[i]!=="object")
throw "The parameter "+i+"("+arguments[i]+") is expected to be an object.";
for(var o in arguments[i]){
if(!this[o]){
b=false;
break;
}
}
if(!b)
break;
}
return b;
},
become:function(){
if(arguments.length<1)
throw "This function need at least one parameter.";
for(var i=0,len=arguments.length;i<len;i++){
if(typeof arguments[i]!=="object")
throw "The parameter "+i+"("+arguments[i]+") is expected to be an object.";
for(var o in arguments[i])
this[o]=this[o]||arguments[i][o];
}
return this;
},
derive:function(){
var F=function(){};
F.prototype=this;
var res=new F;
for(var i=0,len=arguments.length;i<len;i++){
if(typeof arguments[i]!=="object")
throw "The parameter "+i+"("+arguments[i]+") is expected to be an object.";
for(var o in arguments[i])
res[o]=arguments[i][o];
}
return res;
}
};
})();
It’s very easy to use.
If you want to create a top-most person class with name property, you can write like bellow.
var Person=MUI.object.derive({name:"Undefined Name"});
Then, if you want to derive some classes from the class…
var Teacher=Person.derive({subjects:[]});
var Author=Person.derive({books:[]});
var Seller=Person.derive({items:[]});
You can also derive a class from multiple classes…
var TeacherAndSeller=Teacher.derive(Seller);
You can create an object from a class…
var teacher=Teacher.derive({
name:"Peter Smith",
subjects:["Physics","Mathematics"]);
A teacher may become an author…
teacher.become(
Author.derive({
books:["Principle of Physics", "Applied Mathematics"]
})
);
is function is very useful…
alert(Author.is(Person)); //true
alert(Teacher.is(Person)); //true
alert(Seller.is(Person)); //true
alert(TeacherAndSeller.is(Teacher)); //true
alert(TeacherAndSeller.is(Seller)); //true
alert(Author.is(Teacher)); //false
alert(teacher.is(Teacher)); //true
alert(teacher.is(Author)); //true
alert(teacher.is(Seller)); //false
alert(teacher.is(Person)); //true
That’s all of it.
How do you feel about this?
Please visit my link.