Class and Inheritance in Javascript ES5

** classes are used to create objects that has same properties and functions. for example {name: "john", age: 29}, {name: "jane", age: 28}, the same properties but different values.
** instances are the objects that created from classes.
** a constructor is the class function that creates instances.
** inheritance is extending a class to another to add more properties/functions.


Class can be declared and inherited(extended) using keywords - class and extends in Javascript ES6 version, but yet not every browsers support ES6 so it's good to know how to define and inherit classes in Javascript ES5 way especially ES5 way is still valid in ES6

Defining Classes

function Human(name){
  this.name = name;
}
Human.prototype.sayHi = function(){
  console.log("Hi");
};
Human.prototype.introduceMyself = function(){
  console.log("My name is " + this.name);
};

It's Human class that has name as property / sayHi and introduceMyself as it's functions. first a constructor function  was defined as  "function Human(name)" and then the property functions was defined. Every property function should be defined under prototype.

Let's create an instance of Human.

var k = new Human("K");

k.sayHi();
// "Hi"

k.introduceMyself();
// "My name is K"

To create an instance, constructor function should be used with new keyword. every instance of Human has the name property and sayHi/introduceMyself functions but a different value for name depends on what value was used for it like new human("K"); 

Class Inheritance

Classes can be also inherited to extend the functionalities.

function Student(name, school){
  this.school = school;
  Human.call(this, name);
}
Student.prototype = Object.create(Human.prototype);
Student.prototype.constructor = Student;
Student.prototype.introduceMyself = function(){
  Human.prototype.introduceMyself.call(this);
  console.log("My school is " + this.school);
};

It's Student class that extends Human. school is added as the constructor parameter.
school is assigned to this, but name is passed to Human constructor with this.

Parent(Human) functions are assigned to Student through Student.prototype = Object.create(Human.prototype);. However it overwrite constructor too, so constructor should be reset through Student.prototype.constructor = Student;.

introduceMyself is extend function of the parent function. It calls the parent function through Human.prototype.introduceMyself.call(this); and then do more stuffs.

var l = new Student("L","M");

l.sayHi();
// "Hi"

l.introduceMyself();
// "My name is L"
// "My school is M"

Even though Student does not has sayHi function, it's still available since it extends Human.

introduceMyself also extended.

Comments

Add Comment

Login with SNS account to write comments. see details

UP