问题描述
如所言,我们可以在JavaScript中使用闭包,因此它们非常方便地处理安全数据。
As Douglas Crockford says we can have private properties using closures in JavaScript and they are very handy to handle secure data.
现在我理解了封装的概念,因为它帮助我们管理和构建代码。即使私有变量对性能也有用,例如:可以缓存DOM元素,属性和全局变量用于迭代访问。
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.
所以问题是:闭包或私有变量如何帮助我们处理敏感数据?
推荐答案
您可以将代码的某个组件的数据与其余代码进行比较。或者您可能已经在您的网页中包含的任何第三方脚本。因此,您可以保护任何敏感的中间数据不被利用通过XSS攻击。
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.
虽然DOM中存在的任何数据(例如输入元素)都可以通过页面中的任何脚本访问。但是javascript中的一些变量可以在闭包范围内关闭,使得任何其他脚本几乎不可访问。
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;
}
这篇关于私有变量和闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!