当我阅读PrototypeJS的文档时,我遇到了这个主题:它的 Identity Function.我做了一些进一步的搜索和阅读,我认为我理解它的数学基础(例如,乘以1是一个身份函数(或者我误解了这个?) ),但不是
是否有更深入的见解与此相关?为什么Prototype提供这个功能?我可以用它做什么?
谢谢 :)
使用Identity函数可以使库代码更容易阅读.采用 Enumerable#any方法:any: function(iterator, context) {
iterator = iterator || Prototype.K;
var result = false;
this.each(function(value, index) {
if (result = !!iterator.call(context, value, index))
throw $break;
});
return result;
},
它允许您检查数组中的任何元素是否在布尔上下文中为真.像这样:
$A([true, false, true]).any() == true
但它也允许您在检查true之前处理每个元素:
$A([1,2,3,4]).any(function(e) { return e > 2; }) == true
现在没有身份功能,你必须编写任何函数的两个版本,一个如果你预先处理,一个如果你没有.
any_no_process: function(iterator, context) {
var result = false;
this.each(function(value, index) {
if (value)
throw $break;
});
return result;
},
any_process: function(iterator, context) {
return this.map(iterator).any();
},
