2014-01-22 52 views
0

我想了解部分函数。我发现这个例子(http://blog.thesoftwarecraft.com/2013/05/partial-functions-in-javascript.html),我无法完全理解。javascript部分函数,​​参数

function partial(f) { 
    console.log(f) // tip(p,check) 
    var args = Array.prototype.slice.call(arguments, 1); //0.2 

    var test_args = Array.prototype.slice.call(arguments); 
    console.warn(test_args) // [tip(p,check), 0.2] 

    return function() { 
     console.warn(arguments) //[120, 0, [120, 90, 180]] [90, 0, [120, 90, 180]] ... 
     //where do these arguments come from? why don't appear at test_args? 

     var other_args = Array.prototype.slice.call(arguments); //[120, 0, [120, 90, 180]] [90, 0, [120, 90, 180]] ... 

     console.log(args.concat(other_args)) // added percentage to array[0.2, 120, 0, [120, 90, 180]] 

     return f.apply(null, args.concat(other_args)); //we execute tip with all the arguments (only 2 first will be used) 
    } 
} 

function tip(percentage, check) { 
    return check * percentage 
} 

[120, 90, 180].map(partial(tip, 0.2)); //[24, 18, 36] 
+0

根据你的问题,你需要阅读['Array#map'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) ,而不是部分功能。 (并仔细检查你在评论中写下的值,'[90,0,[120'应该是'[90,1,[120'。] – DCoder

+0

[arguments](https://developer.mozilla.org)/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments),[partial application](http://benalman.com/news/2012/09/partial-application-in-javascript/#partial-application) – Andreas

回答

0
return function() { 
    console.warn(arguments) //[120, 0, [120, 90, 180]] [90, 0, [120, 90, 180]] ... 

在哪里这些争论从何而来?为什么不出现在test_args?

因为它是一个新功能 - 返回的 - 它有一个新的arguments对象。您可以点击这里:

var tipper = partial(tip,0.2); 
[120, 90, 180].map(function(el) { 
    console.log(arguments); // here they are! 
    return tipper(el); 
}); 
1

在编程语言理论这个被称为部分应用程序。它基本上需要你的功能,需要ñ参数和N-K参数和返回,通过局部应用这些提供N-K参数有ķ参数的函数。

取本实施例中的伪代码

function mul(x, y) 
    return x*y 

function mul2 
    return mul(2) 

var a = f(1,2); // 3 
var b = mul2(4); // 8 

虽然功能需要两个参数(Ñ),则可以通过仅应用1参数(n-k个)进行另一个功能出来。新功能将只需要一个参数(k)。

您的partial采用函数及其arguments。它将这些参数存储在args变量中。然后它返回内部函数,它本身接受它的参数,但是因为它必须将顶级函数的参数与内部函数的参数结合起来,所以你有concat,并且完整列表被传递给原始函数。

编辑:正如Andreas在评论中指出的那样,这不叫currying。但答案的其余部分仍然成立。

+0

[柯里与部分应用程序有什么区别](http://stackoverflow.com/questions/218025/what-is-the-difference-between-currying-and-partial-application) – Andreas

+0

@安德里亚斯:谢谢你澄清。 –