Archive for August, 2009

JavaScript Inheritance: modify property in parent class

Tuesday, August 11th, 2009

In the following code, there’s a problem which is faced when we’re using inheritance through prototype.

Now, we have a parent class Person, and we have a child class Student which inherit from Person. As a default, we want to set gender to “Male”.

var Person = function(){
    this.object = {"name": "", "gender": "Male"};
}

Person.prototype.sayHi = function(){
    console.log ("Hi! I am " + this.object.name);
}

Person.prototype.sayGender = function(){
    console.log ("I am " + this.object.gender);
}

var Student = function(){}
Student.prototype = new Person();

var victoria = new Student();
victoria.object.name = "Vitoria";
victoria.object.gender = "Female"
victoria.sayHi();
victoria.sayGender();

var sam = new Student();
sam.object.name = "Sam";
sam.sayHi();
sam.sayGender();

here’s the result:

Hi! I am Votoria
I am Female
Hi! I am Sam
I am Female

As we see, the default gender “Male” has been alter to “Female”. we can prevent the default gender in the Person class to be altered by adding “Person.apply(this);” Student class.

After added, the code will look like this:

var Person = function(){
    this.object = {"name": "", "gender": "Male"};
}

Person.prototype.sayHi = function(){
    console.log ("Hi! I am " + this.object.name);
}

Person.prototype.sayGender = function(){
    console.log ("I am " + this.object.gender);
}

var Student = function(){
    Person.apply(this);
}
Student.prototype = new Person();

var victoria = new Student();
victoria.object.name = "Vitoria";
victoria.object.gender = "Female"
victoria.sayHi();
victoria.sayGender();

var sam = new Student();
sam.object.name = "Sam";
sam.sayHi();
sam.sayGender();

here’s the result:

Hi! I am Votoria
I am Female
Hi! I am Sam
I am Male