Javascript Class

Class is kind of like a function in Javascript which are capable to combine multiple method and create objects. Constructor of class are used to initialize the initial value of particular object variable. We can define of class using following syntax.

//class Syntax
class ClassName{
  //constructor of class
  constructor(parms){
    //variable initialization here
  }
  method(variables){
    //Method of class
  }
}

That is basic formal syntax of class. class keyword are used to define custom class followed by the name of class. within curly braces are define class methods and properties. Let see an example to understand class concept.

class Employee{
  //Set initial values
  constructor(name,occupation,salary){
    this.name = name;
    this.occupation = occupation;
    this.salary = salary;
  }
  //Display values of object instance variable
  information(){
    console.log("name : ",this.name);
    console.log("occupation : ",this.occupation);
    console.log("salary :",this.salary);
    console.log("--------------");
  }
}
//Create object of class Employee
let doctor = new Employee("Joly","doctor",40000);
let developer = new Employee("Ruby","developer",100000);
let teacher = new Employee("Hery","teacher",35000);

//Get details 
doctor.information();
developer.information();
teacher.information();
name :  Joly
occupation :  doctor
salary : 40000
--------------
name :  Ruby
occupation :  developer
salary : 100000
--------------
name :  Hery
occupation :  teacher
salary : 35000
--------------

In this example Employee class are creating three different objects. constructor() method are allocate memory of objects and set the value of instance variables. Let see how to first create first object of Employee class.

//Create a object of class Employee
let doctor = new Employee("Joly","doctor",40000);

In this situation first executed constructor of employee class and assign the value of object variables. Reference of object are returning by constructor and its are stored in doctor variable.

Create object of class

This similar ways creating two other objects of Employee class.

let developer = new Employee("Ruby","developer",100000);
let teacher = new Employee("Hery","teacher",35000);
Implementing multiple objects of same class

That is interesting, Each objects of class are capable to access all method of class. object name and dot operator are execute method of class. That is very basic overview of class in Javascript. If you are know about Object oriented programming concept then that can be very easy to you'll. If you are know about OOPS concept then don't worry, here include all basic example.

Basic Class concept in Javascript

In Javascript class there are several concepts. But here are given few most important point which are very important to development perspective.

Class Type

Every custom class name is indicates described its type are function. We can check class type using typeof.

class Student{
  //class logic here
}
console.log(typeof Student);
Class Type are function
//output
function

Using object instance variable

When created an object using new and class constructor. Then each time constructor allocates memory to class instance variables. This instance variable can be access within the class and is also possible to use variable value outside the class using class objects.

class Developer{
  //Set initial value
  constructor(about){
    //this keyword are indicate object variable
    this.about = about;
  }
  info(){
    //Using object variable within the class
    console.log("Who are you? .. ",this.about);
  }
}
var coder = new Developer("Programmer");

var tester = new Developer("Tester");

//Execute method of class
tester.info();
//using object variable outside of the class
console.log("Hello",tester.about);

//Execute method of class
coder.info();
//using object variable outside of the class
console.log("Hello",coder.about);
Who are you? ..  Tester
Hello Tester
Who are you? ..  Programmer
Hello Programmer
Using object instance variable

When executing method by class object, Then Inside a class method, (this) keyword are used to get instance object variables. When assign this object to another variable then in this case both variable are work on same object reference.

Executed Class Method

There are two ways to execute class methods. First way is to using of class object. And second way is possible to class method are call within the class method using this keyword. But first object are execute class method then possible to work second way.

class MyMaths{
  
  constructor(num1,num2){
  
    this.num1=num1;
    this.num2=num2;
  }
  multiply(){
    console.log("multiply is :",(this.num1*this.num2));
  }
  sum(){
    console.log("Sum is :",(this.num1+this.num2));
    //execute class method
    this.multiply();
  }
  operation(){
    //call on class method
    this.sum();
  }
  
}
var obj = new MyMaths(3,7);
obj.operation();
Sum is : 10
multiply is : 21

Object Referencing

In above example variable are hold the reference of class objects. and variable which are hold the reference, those is called an object of class.

class Test{
  
  constructor(){
    this.data=10;
  }
  setData(newData){
    this.data=newData;
  }
  info(){
    console.log("data : ",this.data);
  }
  
}
var objFirst = new Test();

//Assign reference
var objSecond = objFirst;

objFirst.info();
objSecond.info();

//When modified data value to any object

objFirst.setData(20);

//After modified
objFirst.info();
objSecond.info();
Object Reference Example
data :  10
data :  10
data :  20
data :  20

Clone of object

In above example you'll can see example when assign one object to another object so both object variable are work on same instance variables. In case you'll are try to copy a object instance variable into to another objects then there are many possibility and methods are available in Javascript.

First copy instance variable: There is two main method available in Object class which are copy a instance variable into new object.

Object.assign({}, copyObject);
JSON.parse(JSON.stringify(copyObject));

This two method are convert any class objects to Object class object. That means supposed custom class like Record object are clone to Object class object. This created object is not capable to use methods of custom class.

Copy instance variable and method: That is actually copy class object instance variable and method to custom class. new copy object is capable to use all method and properties of same class.

Object.assign(
    Object.create(
      Object.getPrototypeOf(copyObject)
    ),
  copyObject
);

copyObject is actual object which is to clone. Let see an example.

class Record{
    constructor(img,docs){
        this.img=img;
        this.docs=docs;
    }
    info(){
        console.log("Total Images : ",this.img);
        console.log("Total Document : ",this.docs);
    }
    //copy objects
    copyObject() {
      return Object.assign(
        Object.create(
          Object.getPrototypeOf(this)
        ),
        this
      );
    }
}

var recordSet = new Record(100,200);
//Create objects using class instance variable
var firstClone = Object.assign({}, recordSet);
var secondClone = JSON.parse(JSON.stringify(recordSet));
var thirdClone = recordSet.copyObject();
console.log(recordSet);
console.log(firstClone);
console.log(secondClone);
console.log(thirdClone);

thirdClone.info();
Record { img: 100, docs: 200 }
{ img: 100, docs: 200 }
{ img: 100, docs: 200 }
Record { img: 100, docs: 200 }
Total Images :  100
Total Document :  200
Clone of Objects in javascript

firstClone and secondClone is type of Object class. For more clarity check all objects constructor name.

//obj.constructor.name 
console.log(recordSet.constructor.name);
console.log(firstClone.constructor.name);
console.log(secondClone.constructor.name);
console.log(thirdClone.constructor.name);
Record
Object
Object
Record

Get name of class properties and method

When you'll are try to access class all methods and properties using class name in this situation we can use Object.getOwnPropertyNames() method. This method are take one parameter which is name of class. And this method are return array of all methods if class are not define any method then this method returning empty array.

var methods = Object.getOwnPropertyNames(Array.prototype);

console.log(methods);
[ 'length',
  'constructor',
  'concat',
  'find',
  'findIndex',
  'pop',
  'push',
  'shift',
  'unshift',
  'slice',
  'splice',
  'includes',
  'indexOf',
  'keys',
  'entries',
  'forEach',
  'filter',
  'map',
  'every',
  'some',
  'reduce',
  'reduceRight',
  'toString',
  'toLocaleString',
  'join',
  'reverse',
  'sort',
  'lastIndexOf',
  'copyWithin',
  'fill',
  'values' ]

Same result produce when use object of class.

var arr=[];
var methods = Object.getOwnPropertyNames(Object.getPrototypeOf(arr));

console.log(methods);


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved