April 2003
Inheritance in a Prototype Based Language
We use Javascript to show how OO inheritance features can be used in a prototype based language.
This example will not take advantage of the prototype delegate feature of Javascript. Instead we will use real prototype based logic, and remove any need for the new operator.
Creating the Base Class
- First a newObject is created, and then attributes are added, this includes the methods that can be called on this object specifically.
The aObject function is responsible for making general objects and is synonymous with a base class. This is the only place where we use the new operator, and even then it can be removed by using the function instance that is created when the function is called. In this example, all objects can say hi.
-
aObject = function(){
var newObject=new Object();
newObject.sayHi=function(){
alert("Hi");
}//sayHi
return newOjbect;
}//aObject
Inheriting Attributes/Properties
The idea is to call the parent class to add attributes and then override the those attributes if we desire. The aPerson class is a little more forward with providing his name.
aPerson = function(firstName, lastName){
var newPerson=aObject();
newPerson.firstName=firstName;
newPerson.lastName=lastName;
newObject.sayHi=function(){
alert("Hi, my name is "+firstname+" "+lastName);
}//sayHi
return newPerson;
}//aObject
Conclusion
It can't be much simpler than that. We could add an attribute to aObject that refereed to the class of the object and be sure to update it for each of the decedents, this would be useful for performing typeOf() operations.
April 2002: First writing