September 23, 2018

Encapsulation with closures in javascript

Javascript supports many programming styles like Object oriented and functional. Functional style in Javascript allows new ways of programming for programmers already having knowledge of languages like C++ or java.

 Javascript supports first class functions. Javascript originally has lexical scoping of variables. This means that you can declare and define functions not only at global level but also inside other functions. With lexical scoping, a function has access to all variables in the ascendant functions. Inner functions, when returned from outer function keep reference to the variables of outer function even after outer function exits. These variables can only be accessed by the inner functions.

This restricted visibility of outer function variables allow encapsulation of data. Following is an example of such a case.

/* Function hiding variable h.
    It returns two function closures. */
    function fn () {
    var h = 0;
    /* Return object with two methods as properties.
        These methods have access to hidden variable h. */
    return {

        // Overwrite variable h
        set : function(v) { h = v; },
        // Read variable h and print.
        log : function() { console.log(h); },
    }
    }  

// Test above function
var ret = fn();
var ret2 = fn();
ret2.set(10);
ret.log();
ret2.log();

/* Output is  
    0
    10
*/

fn is outer function. it returns an object with two functions set and log as properties. The inner functions are function closures that have reference to outer function variables.

The function fn is invoked twice with return values assigned to ret and ret2 variables. Then set function is invoked on ret2 to overwrite the hidden variable of ret2. Finally, we log the values to see that ret and ret2 has separate copies of variable h.


No comments:

Post a Comment