Private variables and closures

你。 提交于 2019-12-14 03:57:29

问题


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?


回答1:


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;
}


来源:https://stackoverflow.com/questions/13101968/private-variables-and-closures

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!