Toll Free 88808-24000 sales@treewalkerlabs.com

Closures is concept functions have access to variables that were available in the scope where the function was created.

To understand it fully below are the set of examples which will help you to understand:

var Car = function(model){

this.model = model; // member variable to the car function

}

var car = new Car(“Audi S3”); // Creates the object of the car class using new keyword

consloe.log(“Car Model : “+car.model) // output : Car Model : Audi S3

Now I will do some changes in the Car class to explain what closure is :

var Car = function(model){

_model = model; // local variable within the car function

}

var car = new Car(“Audi S3”); //¬†Creates the object of the car class using new keyword

consloe.log(“Car Model : “+car._model) // Error : _model not referenced

Because the model is local to Car function it cannot be accessed and remembered by Car function.To fix the above issue we need to write a closure or member function which will have the access to the variable .

var Car = function(model){

_model = model; // local variable within the car function

this.getModel = function (){

return _model;

}

}

var car = new Car(“Audi S3”);

consloe.log(“Car Model : “+car.getModel ()) // It will display the Audi S3,

So we can see even after the code has been executed , the car object had access to the local variable “_model” within the getModel scope.