简体   繁体   English

此功能实际上在做什么?

[英]What is this function actually doing?

I'm reading about Function currying in Javascript. 我正在阅读有关Java 函数泛滥的信息。 I got the concept and the examples were easy to understand. 我明白了这个概念,例子很容易理解。

But then, the author of the article says that currying a function too much can be messy as for the multiple nested return s, and shows a function to curry another function passed as argument. 但随后,该文章的作者说,讨好的功能太多可能会搞得一团糟作为多重嵌套返回小号,并显示一个功能咖喱作为参数传递的另一个功能。

var curryIt = function(uncurried) {

var parameters = Array.prototype.slice.call(arguments, 1);

return function() {
   return uncurried.apply(this, parameters.concat(
     Array.prototype.slice.call(arguments, 0)
    ));
  };
};

Then applies it this way 然后以这种方式应用

var greeter = function(greeting, separator, emphasis, name) {
  console.log(greeting + separator + name + emphasis);
};

var greetHello = curryIt(greeter, "Hello", ", ", ".");

greetHello("Heidi"); //"Hello, Heidi."
greetHello("Eddie"); //"Hello, Eddie."

curryIt is the function that curries another function. curry咖喱另一个功能的功能。 How exactly is doing that? 到底是怎么做到的?

Though there is no unfamiliar code to me I seem not to get it. 尽管没有我不熟悉的代码,但我似乎没有得到。

Technically, this is partial application but the two ideas are very closely related. 从技术上讲,这是部分应用,但是这两个想法非常相关。

Anyway, let's break down your code: 无论如何,让我们分解一下代码:

var curryIt = function(uncurried) {
  // Get all of the parameters except for `uncurried`
  var parameters = Array.prototype.slice.call(arguments, 1);

  // Return a new function such that...
  return function() {
    // The function you passed in, `uncurried` is called
    return uncurried

      // apply - Use an array for arguments instead of positional arguments
      // i.e, f(a, b, c) === f.apply(this, [a, b, c])
      .apply(

        // Set the value of `this` in `uncurried`
        this, 

        // Create a copy of the original `parameters` array and add...  
        parameters.concat(

          // ...the arguments that were passed to the anonymous function
          Array.prototype.slice.call(arguments, 0)
      ));
  };
};

By looking at how parameters changes, you can get a feeling for how it works. 通过查看parameters变化,您可以了解其工作原理。

 var curryIt = function(uncurried) { var parameters = Array.prototype.slice.call(arguments, 1); console.log('curryIt: ' + parameters.join(' ')); return function() { var newParams = Array.prototype.slice.call(arguments, 0); console.log('anonymous: ' + newParams.join(' ')); // Prepare the arguments here so we can see them var args = parameters.concat(newParams); console.log('Full call: ' + args.join(' ')); return uncurried.apply(this, args); }; }; function f(a, b, c, d) { console.log('Finished: ' + [a, b, c, d].join(' ')); console.log(' '); } var g = curryIt(f, 1, 2); g(3, 4); g(10, 20); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM