"身份功能"的目的是什么?

Jor*_*enB 4 prototypejs

当我阅读PrototypeJS的文档时,我遇到了这个主题:它的身份功能.我做了一些进一步的搜索和阅读,我认为我理解它的数学基础(例如乘以1是一个身份函数(或者我误解了这个?)),但不是为什么你会写JS(或PHP或C或其他)函数,基本上将X作为参数,然后只是做类似的事情return X.

是否有更深入的见解与此相关?为什么Prototype提供这个功能?我可以用它做什么?

谢谢 :)

der*_*red 7

使用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;
  },
Run Code Online (Sandbox Code Playgroud)

它允许您检查数组中的任何元素是否在布尔上下文中为真.像这样:

$A([true, false, true]).any() == true
Run Code Online (Sandbox Code Playgroud)

但它也允许您在检查true之前处理每个元素:

$A([1,2,3,4]).any(function(e) { return e > 2; }) == true
Run Code Online (Sandbox Code Playgroud)

现在没有身份功能,你必须编写任何函数的两个版本,一个如果你预先处理,一个如果你没有.

  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();
  },
Run Code Online (Sandbox Code Playgroud)