Javascript-Closures - (2)

 


πŸ‘‰Closures

✅Use of Closures

1)Maintain states between function calls
2)Access private variables

function Fun1(val){
        var str = val;
}
Fun1("John");
Fun1("Smith");

Each call to a function assigns the value, and the variable is deallocated at the end of the function.

So, to maintain the state between function calls and access private variables, closures are used.

Closure is a function inside a function. When you create a function, it's private, when you return it, it becomes public.

function Fun1(val){
        var str = val;
        var _getdata = function() { //private function
                 return str; //encloses to maintain the state
        }
        return {
                getData : _getData //public access
        };
}

var t = Fun1("John Smith");
alert(t.getData());
alert(t.getData());
alert(t.getData());

Each alert gives the value "John Smith". Because of closure, the variable is enclosed, and the state is maintained.

Comments

Popular posts from this blog

SQL-ForeignKeyConstraint-Page6

Javascript-OOPs(Part3)-Inheritance - (9)

OraclePLSQL-Page3