“身份函数"的目的? [英] Purpose of an 'Identity Function'?
问题描述
我在阅读 PrototypeJS 的文档时遇到了这个主题:它的 身份函数一>.我对它做了一些进一步的搜索和阅读,我想我理解它的数学基础(例如,乘以 1 是一个恒等函数(或者我误解了这个?)),但不是为什么你会写一个JS(或 PHP 或 C 或其他)函数,它基本上将 X 作为参数,然后执行诸如 return X
之类的操作.
I came across this subject when I was reading through PrototypeJS's docs: its Identity Function. I did some further searching&reading on it and I think I understand its mathematical basis (e.g. multiplication by 1 is an identity function (or did I misinterpret this?)), but not why you would write a JS(or PHP or C or whatever)-function that basically takes X as a parameter and then just does something like return X
.
是否有更深入的见解与此相关?Prototype 为什么提供这个功能?我可以用它做什么?
Is there a deeper insight connected to this? Why does Prototype supply this function? What can I use it for?
谢谢:)
推荐答案
使用 Identity 函数使库代码更易于阅读.采用 Enumerable#any 方法:
Using the Identity function makes the library code slightly easier to read. Take the Enumerable#any method:
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;
},
它允许您在布尔上下文中检查数组的任何元素是否为真.像这样:
It allows you to check if any of the elements of an array are true in a boolean context. Like so:
$A([true, false, true]).any() == true
但它也允许您在检查是否为真之前处理每个元素:
but it also allows you to process each of the elements before checking for true:
$A([1,2,3,4]).any(function(e) { return e > 2; }) == true
现在如果没有恒等函数,您将不得不编写任何函数的两个版本,一个用于预处理,另一个用于不处理.
Now without the identity function you would have to write two versions of any function, one if you pre process and one if you dont.
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();
},
这篇关于“身份函数"的目的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!