Basic Inheritance in Pure JavaScript

JavaScript is a powerful Prototype Based Object Oriented scripting language.

This starting sentence is stating many facts about this language such as:

  1. Of course it is powerful ...
  2. Object Oriented languages are either Class Based (like C++, Java, ...) Or Prototype Based (like JavaScript, ActionScript, ...)
  3. It is a Scripting language which means it is interpreted not compiled (programming languages are compiled)

So, we are trying to show how to implement inheritance in a pure Prototype Based fashion, and we do not go for those framework specific solutions which are trying to bring Class Based fashion to JavaScript!

Scenario:
There is no better example than human beings for Object Orientation.

Father Class: Human
Child Class: Teacher

Anything could be a function in JavaScript so our Human class (Human function) would be like this:

function Human(name){ 
  this.name=name;  
}
 
Human.prototype.introduce=function(){ 
  alert("I am " + this.name)
}

// usage would be like this:

var john = new Human("John Smith");
john.introduce();


Now we write the Teacher class (Teacher function) which is extending Human.

// Here's where the inheritance occurs 
Teacher.prototype = new Human();        

// Otherwise instances of Teacher would have a constructor of Human 
Teacher.prototype.constructor = Teacher;       

function Teacher(name, field) { 
  this.name = name;
  this.field = field;
} 

Teacher.prototype.professionalIntroduce = function(){ 
  alert("My name is " + this.name + " and I am a " 
  + this.field + " teacher.");
} 

// usage
var marry = new Teacher("Marry Brown", "Chemistry");
marry.introduce();
marry.professionalIntroduce();


Download

No comments:

Post a Comment