JavaScript - Function

[ECMAScript 5]


function expression vs function declaration
-------------------------------------------------------------
function expression - abc = function() {  console.log("i get called")};
function declaration  - function abc() {  console.log( "no logging here" )}

function expression gets called once.




Closure

  • Closure is a pattern by which a function can maintain access to variables of the outer function even after the outer function completes execution.
  • This is possible as the inner function saves context to static scope of the parent.
  • Closure is a pattern to emulate private variable in JS
  • One ways to implement is by returning the nested function and the outer function calling itself.
  • Second way is described below where the return is Object which has multiple functions that can access the variable/static scope.
function encloses(){

    var x = 100;

    return {
        increment : function(){ x++ ; return x;},
        decrement : function(){x-- ; return x;}
    }
}


var closure = encloses();

console.log(closure.increment()); //101
console.log(closure.decrement()); //100
console.log(closure.decrement()); //99

No comments:

Post a Comment