Object Oriented Programming in JavaScript: Part 1


JavaScript is a prototype-based programming style of object-oriented programming in which classes are not present.

It can support OOP because it supports inheritance through prototyping as well as properties and methods.

Object Oriented Programming in JavaScript is known as prototype-based programming.

  1. Creating Class in JavaScript

    the following syntax is used for declaring a class in JavaScript:
    1. function Emp() {  
    2.     alert('Emp instantiated');  

    Here Emp can act as a class in JavaScript.

    The body of Emp acts as a constructor and is called as soon as we create an object of the class.
  2. Creating Objects of Emp Class

    Using the following syntax we can create an object of the Emp class:
    1. var Emp1 = new Emp(); 
    As soon as we create an object of the Emp class the constructor will be called.

    Here the above function Emp would be treated as a class in JavaScript.

    class in JS
  3. Running the code

    Running the code

    An alert will be shown on the page load of the web form.
  4. Properties of class

    We can define the properties of a class in the following way:
    1. function Emp(firstname) {  
    2.     alert('Emp instantiated');  
    3.     this.firstname = firstname;  

    • Passing value to properties
      1. var Emp1 = new Emp("Devesh is Emp of GENPACT INDIA");  
      2. alert(Emp1.firstname); 
    • Snap for defining properties


    • Complete code

      Complete code
    • Running code

      Running code

      When we run the code we get an alert of the string that we are passing to the Emp class.
      1. var Emp1 = new Emp("Devesh is Emp of GENPACT INDIA"); 


This document contains the basics of OOP in JavaScript.