我是函数式编程的新手,学习了currying和部分应用程序,以及闭包在函数应用程序中currying和partial应用程序实现中的作用。问题是,我们是否真的只在数据隐私方面使用closure和部分应用程序?
发布于 2019-10-20 16:32:57
这取决于你所说的数据隐私。
如果数据隐私意味着“确保您的用户隐私是安全的”,那么不是。闭包允许创建curried函数,但人们仍然可以做一些愚蠢的事情:
const greetings = intro => name => {
tweet(`Hello everybody! ${name} just executed this program`); //<~ waaat?!
alert(`${intro} ${name}!);
};如果数据隐私意味着“我如何保护一些数据不被其他程序访问”,那么它是可以做到的。例如:
在这个版本中,人们仍然可以篡改value
function volume_controls(value) {
this.value = value;
}
volume_controls.prototype.up = function () {
this.value = this.value + 1;
};
volume_controls.prototype.down = function () {
this.value = this.value - 1;
};
var ctrl = new volume_controls(10);
ctrl.up(); //=> 11
ctrl.value = "boom";
ctrl.up(); //=> "boom1"有了闭包,这将是不可能的:
const volume_controls = value => ({
up: () => ++value,
down: () => --value
});
const ctrl = volume_controls(10);
ctrl.up(); //=> 11
ctrl.value = "boom"
ctrl.up(); //=> 12尽管从函数式编程的角度来看,篡改参数并不好。
https://stackoverflow.com/questions/58471005
复制相似问题