Thursday, 8 March 2018

explain closures in javascript

case 1-

var x = function(passed){
  var internal= 2;
  return passed + internal;
};

console.log(x(3));  //5


case-2
note:- removed passed which is passing as argument in x() function

var passed = 3; //lexical scope

var x = function(){
  var internal= 2;
  return passed + internal;
};

console.log(x());  //5

var passed = 4;

console.log(x());  //6


case -3

  var addNum = function(passed){

    var add = function(inner){
       
       return passed + inner;
    };
    
    return add;
};

var addThree = new addNum(3);
//console.dir(addThree); 

var addFour = new addNum(4);
//console.dir(addFour); 


console.log(addThree(1)); //4
console.log(addFour(2)); //6

case - 4
exp -

function expClosure(){
   var counter = 1;
 
   return{
      increment: function(){
        counter++;
      },
      Print: function(){
       console.log(counter);
     }
   }
}

var cl = expClosure();

cl.increment();

cl.Print(); //2

exp:-

var getName = function(firstName, lastName){
   var inititial="Hi, Mr";
 
   var makeFullName = function(){
      return inititial +" " + firstName + " " + lastName;
   }
 
   return makeFullName();
}

var name = getName('Ashish','Verma');
console.log(name);  // Hi, Mr Ashish Verma







No comments:

Post a Comment