Object Oriented Programming in JavaScript

 

So here we are going to learn how we can do Object oriented programming in JavaScript. We can Implement Inheritance, Encapsulation, Abstraction and Polymorphism concept in JavaScript.

Whenever we talk about Object oriented programming then concepts of "Class, Object, Property, Method, Constructor" etc are added by default and you must understand all of them.

I am starting by assuming that you guys are aware of all above concepts. If not then please go through them, then it would be easier for you to understand this article. Also you must have basic understanding of JavaScript (e.g. variable, functions etc.).

To understand Class, Method, Object, Constructor and Property Please refer my article Object Creation in JavaScript .

Class: In JavaScript there is no keyword 'class' like you found in other languages such as C++ or Java. In JavaScript defining a class is same as defining function.

eg. MyClass = function(){};

Note**: ECMA 6 onward keywords like 'class, extends etc.' got added in JavaScript.

Object: Instance of Class is an Object. so when we say "var myObj = new MyClass();" then myObj is Object of MyClass.

Method: Any function which is part of class is method.

Constructor: In JavaScript there is no separate function to create constructor like we do in C++ or Java. In JavaScript the function serves itself as the Constructor of object. So in JavaScript there is no need to define constructor explicitly.

Property: any attributes you create as part of the function or so called Class are Property of that class.

 

Let's understand Class, Object, Property, Method and Constructor by example.

 

function Person(){
    //Property of Person class
     var firstName; 
     var lastName;
   //Method of class Person
	function showDetails(){
        console.log(firstName+" "+lastName);
    }
}
// Instantiation of Person Class. Also Person is used as constructor.
var p = new Person();
// p is an object of person class and calling method showDetails.
p.showDetails("Deepak", "Singh"); // Deepak Singh

 

Inheritance

JavaScript is prototype based programming language. Prototype-based programming is an OOP model that doesn't use classes, but rather it first accomplishes the behavior of any class and then reuses it (equivalent to inheritance in class-based languages) by decorating (or expanding upon) existing prototype objects. (Also called classless, prototype-oriented, or instance-based programming.)

JavaScript only support single Inheritance. Let's understand this by example.

 

function Shape(name, color) {
  this.name = name;
  this.color = color;
  
  return this;
}

  Shape.prototype.displayShape = function (){
      console.log("Name : "+this.name+" color: "+this.color);
  }

function Rectangle(name, color) {
  // Call the parent constructor, making sure (using Function#call)
  // that "this" is set correctly during the call
  Shape.call(this, name, color);
  // Added extra property to different shapes.
  this.sides = '4';
}
// Create a Rectangle.prototype object that inherits from Shape.prototype.
// Note: A common error here is to use "new Shape()" to create the
// Rectangle.prototype. The correct place to call Shape is above, where we call 
// it from Rectangle. Similarly other shapes (Triangle and Circle) class 
// created and Inherited from Shape class.

Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle; // Reset the constructor from Shape to Rectangle
Rectangle.prototype.changeColor = function (colr){
  this.color = colr;
  console.log("Color Changed for "+this.name);
}

function Triangle(name, color) {
  Shape.call(this, name, color);
  this.sides = '3';
}

Triangle.prototype = Object.create(Shape.prototype);
Triangle.prototype.constructor = Triangle; // Reset the constructor from Shape to Triangle
Triangle.prototype.changeColor = function (colr){
  this.color = colr;
  console.log("Color Changed for "+this.name);
}

function Circle(name, color) {
  Shape.call(this, name, color);
  this.sides = '0';
}

Circle.prototype = Object.create(Shape.prototype);
Circle.prototype.constructor = Circle; // Reset the constructor from Shape to Circle
Circle.prototype.changeColor = function (colr){
  this.color = colr;
  console.log("Color Changed for "+this.name);
}

var rect = new Rectangle('Rectangle', 'red');
var tri = new Triangle('Triangle', 'Blue');
var cir = new Circle('Circle', 'Green');

rect.displayShape(); //Name : Rectangle color: red
tri.displayShape(); // Name : Triangle color: Blue
cir.displayShape();// Name : Circle color: Green

rect.changeColor("blue") //Color Changed for Rectangle
rect.displayShape(); //Name : Rectangle color: blue

tri.changeColor("Green") //Color Changed for Triangle
tri.displayShape(); //Name : Triangle color: Green

cir.changeColor("Red") //Color Changed for Circle
cir.displayShape(); //Name : Circle color: Red

 

Encapsulation

If you see from the above example displayShape method which is part of Shape class is being used by other classes (Rectangle, Triangle and Circle) without knowing the implementation details of displayShape method or defining this method it explicitly in their classes. This is an implementation of Encapsulation.

Information hiding is common feature of Encapsulation, that also you can implement in JavaScript. You can refer my article Closure
concept. Encapsulation.

Abstraction

Abstraction is basically a concept/mechanism help in solving real problem using Inheritance, Composition or Encapsulation.

Polymorphism

 If you see in the above example changeColor method with same name is being used by all the classes. So this is the example of polymorphism.

 
Hope you have got fare understanding of Object Oriented Programming concept in JavaScript.
 
Keep Reading and Keep Learning.
 

Reference: MSDN Introduction to Object Oriented Programming