Monday, March 28, 2011

javascript object oriented programming 2: inheritance

Inheritance - simple way

First, we need to know prototype. We can think prototype as a template. In javascript, everything is an object, every object has its own prototype.

A simple inheritance in javascript:
//constructor method
function Person(name, sex) {
       this.name = name;
       this.sex = sex;
   }
//define Person prototype 
Person.prototype = {
       getName: function() {
           return this.name;
       },
       getSex: function() {
           return this.sex;
       }
}
//define an Employee constructor method
function Employee(name, sex, employeeID) {
    this.name = name;
    this.sex = sex;
    this.employeeID = employeeID;
}
// Make Employee.prototype link to an instance of Person
// The Person instance can call the methods in Person prototype, so Employee's instances can access methods and properties of Person prototype as well.
Employee.prototype = new Person();
Employee.prototype.getEmployeeID = function() {
    return this.employeeID;
};
However, there are some problems with such a simple inheritance.
1. When we create the Employee constructor method and protoype, we also create a Person instance. That is not reasonable.
2. Employee's constructor method cannot access its parent/super class Person's constructor method.
3. Employee's constructor is pointing to the wrong place.
We will see how to address all these problems in my next blog.

No comments: