Sunday, 12 October 2014

Closures in javascript

Before understanding closure we have to know about scopes in javascript

Example 1 :- 
var x = 1; //Global for below functions

function a(){
   x = 2; //refers to Global x 
   var y = 3; //New local variable for func a
   function b(){
      y = 4 ; //refers to parent funct a
      var x = 5;// local variable for func b no relation to global x
   }
b();
}

a();

Closure :- Is nothing but a closed box where inside member variables are accessed only by member functions.

function  person (pName){
     var _name = pName ; // Private variable 
     
    this.getName = function (){
           return _name;
};

}

var human = new person("Ram");

human._name // throws error because its closure to person fun

human.getName() ; // will return name of the person




No comments:

Post a Comment

Custom single threaded java server

 package com.diffengine.csv; import java.io.*; import java.net.*; import java.util.Date; public class Server { public static void main(Str...