我正在阅读Eloquent Javascript,我对这个部分功能示例感到有些困惑.请帮忙解释一下

Sha*_*aan 5 javascript function partial

function asArray(quasiArray, start) {
  var result = [];
  for (var i = (start || 0); i < quasiArray.length; i++)
    result.push(quasiArray[i]);
  return result;
}

function partial(func) {
  var fixedArgs = asArray(arguments, 1);
  return function(){
    return func.apply(null, fixedArgs.concat(asArray(arguments)));
  };
}

function compose(func1, func2) {
  return function() {
    return func1(func2.apply(null, arguments));
  };
}

var isUndefined = partial(op["==="], undefined);
var isDefined = compose(op["!"], isUndefined);
show(isDefined(Math.PI));
show(isDefined(Math.PIE));
Run Code Online (Sandbox Code Playgroud)

为什么函数不能简单地返回:

func1(func2);
Run Code Online (Sandbox Code Playgroud)

并给出适当的输出.我认为存储在变量isUndefined中的部分函数已经返回func.apply(null,[fixed,arguments])

var op = {
"+": function(a, b){return a + b;},
"==": function(a, b){return a == b;},
"===": function(a, b){return a === b;},
"!": function(a){return !a;}
/* and so on */
};
Run Code Online (Sandbox Code Playgroud)

Rus*_*Cam 2

partial都是高阶compose函数。

isUndefined将返回一个函数,该函数在调用时将使用原始参数以及调用时传递的任何新参数来调用最初传递的函数。

要回答您的问题,您将调用apply返回的函数partial,该函数又将调用apply最初传递给 的函数partial

您想要compose返回一个函数,该函数在调用时将返回调用第一个函数的结果,并将第二个函数作为参数传递(第二个函数将传递给调用的参数传递compose)。如果compose返回func1(func2),那么您可以将调用的结果赋给该变量isDefined

编辑:

现在我们已经有了op,让我们尝试分解它:

var isUndefined = partial(op["==="], undefined);
Run Code Online (Sandbox Code Playgroud)

这相当于

var isUndefined = partial(function(a, b){return a === b;}, undefined);
Run Code Online (Sandbox Code Playgroud)

isUndefined被分配一个函数,该函数在调用时将调用作为第一个参数传递给 的函数partial,作为该函数调用的第一个参数传递undefined,后跟传递给该函数的参数,isUndefined

partial(function(a, b){return a === b;}, undefined /* this will become 'a' when isUndefined is invoked */)(argumentForisUndefined /* this will become 'b' when isUndefined is invoked */);
Run Code Online (Sandbox Code Playgroud)

isDefined与另一个函数组合isUndefined,该函数对 的结果求反isUndefined

var isDefined = compose(op["!"], isUndefined);
Run Code Online (Sandbox Code Playgroud)

相当于

var isDefined = compose(function(a){return !a;}, isUndefined);
Run Code Online (Sandbox Code Playgroud)

这相当于(为清楚起见重命名变量)

var isDefined = compose(

    function(a){return !a;}, 

    partial(  /* partial function becomes 'a' passed to first function */
        function(b, c) {
            return b === c;
        }, 
        undefined /* undefined becomes 'b' passed to partial */
    ) 

)(argumentForisDefined /* argumentForisDefined becomes 'c' passed to partial */);
Run Code Online (Sandbox Code Playgroud)

如果我们看看到目前为止我们所拥有的内容并替换可读性,则可以归结为一个函数,该函数接受一个参数并将其与未定义的进行比较,否定结果并返回一个布尔值

var isDefined = function (b) { return !undefined === b; } 
Run Code Online (Sandbox Code Playgroud)