Gurpreet Singh
Gurpreet Singh

Reputation: 21233

Private variables and closures

As Douglas Crockford says we can have private properties using closures in JavaScript and they are very handy to handle secure data.

Now I understand the concept of Encapsulation, as it helps us to manage and structure the code . Even private variables are useful for performance, eg: you can cache DOM elements, properties and global variables for iterative access.

So the question is: How exactly closures or private variables help us in handling the sensitive data?

Upvotes: 3

Views: 555

Answers (1)

lorefnon
lorefnon

Reputation: 13095

You can secure the data of a certain component of your code against the rest of the code. Or maybe any third party scripts you might have included in your page. So you can protect any sensitive intermediate data from being exploited through XSS attacks.

While any data that is present in DOM (say in input elements) is accessible to any script in the page. However some variable in javascript can be closed inside a closure scope making it virtually inaccessible by any other script.


x = {}
(function(){
    var a;

    x.fn = function(arg){
        a = arg;  // Can access and modify a;
    }

})();

function fn2(){
    a = 12; // This does not change the a above;
}

Upvotes: 3

Related Questions