Object Oriented Javascript - 4 : Exercise 1
continuing Object Oriented Javascript - 3 : Function
A Simple Problem
Let us try to create the following simple three objects
- Person – base
- Student – inheriting Person
- Teacher – inheriting Person
Create Person
var Person = function(){
this.name = “”;
this.age = 0;
this.gender = “”;
};
Person.prototype.getDetails = function(){
return (“Name : “ + this.name + “, Age : “ + this.age + “, Gender : “ + this.gender);
};
var person = new Person();
person.name = “Raj”;
person.age = 78;
person.gender = “male”;
jsbin
Let us check the structure of the object person
So here we can see
person
is instantiated from Person
person
inheriting Person.prototype
Person
inheriting Object.prototype
Prototype Chaining
In Javascript the process of inheriting is different from that in Class-Based objects. Here each object is re-using the behavior of the prototype which it is inheriting.
person.__proto__
refers to Person.prototype
person.__proto__.__proto__
refers to Object.prototype
This linking of prototype is called Prototype Chaining. As you can see in the screenshots The final link in the chain will be Object
.
Any property person.__proto__.prop
and person.__proto__.__prop__.prop
can be called as person.prop
, where for prop
the instance will be person
.
Create Student
var Student = function(){
this.grade = “”;
this.group = “”;
};
Student.prototype = new Person();
Student.prototype.register = function(name, age, gender, grade, group){
this.name = name;
this.age = age;
this.gender = gender;
this.grade = grade;
this.group = group;
return “Student Registered”;
};
var student = new Student();
student.register(“Raj”, 8, “male”, 5, “main”);
jsbin
The structure of object student
Create Teacher
var Teacher = function(){
this.subject = “”;
this.level = “”;
};
Teacher.prototype = new Person();
Teacher.prototype.assign = function(name, age, gender, subject, level){
this.name = name;
this.age = age;
this.gender = gender;
this.subject = subject;
this.level = level;
return “Teacher Assigned”;
};
var teacher = new Teacher();
teacher.assign(“Roy”, 38, “male”, “Mathematics”, “A”);
jsbin
The structure of object teacher
which is similar to that of student
Here the structure of both Student
and Teacher
are very similar, because they are simple objects and use the same prototype Person
Here we can see that getDetais
is the function defined in Person
and does not show the properties of Student
and Teacher
when invoked for student
and teacher
. To make it show all the properties we need to find out a way to override getDetais
. Let us try this in the next exercise.