可以通过两种方式调用的单个函数

A single function that can be invoked in two ways

本文关键字:单个 函数 调用 两种 方式 可以通过      更新时间:2023-09-26

我想写一个可以用两种方式调用的函数:

sum(3,5); //8

sum(3)(5); //8

这显然是不够的:

function sum (a,b){
  return a + b;
}

这里是我到目前为止的地方:

http://jsfiddle.net/marcusdei/a8tds42d/1/

你可以这样做:

function sum (a,b){
    if(b == undefined){
        return function(b){
            return a + b;   
        }
    } else {
      return a + b;        
    }
}

为什么(你为什么要这样做? - ans: homework)

function sum (a,b){
    if(b === undefined)
    {
        return function summer(next){
            return a + next;
        }
    }
    return a + b;
}

更新小提琴:http://jsfiddle.net/a8tds42d/2/

就像另一个选择:

function sum (a,b) { 
    if (b === undefined) { 
        return sum.bind(null, a); 
    } 
    return a + b; 
}

您需要的是编写一个curry函数。Kevin Ennis在这里详细介绍了如何实现。

https://medium.com/@kevincennis currying-in-javascript-c66080543528

下面是上面帖子中的函数(以防万一帖子消失了)

function curry( fn ) {
   var arity = fn.length;
   return (function resolver() {
      var memory = Array.prototype.slice.call( arguments );
      return function() {
        var local = memory.slice(), next;
        Array.prototype.push.apply( local, arguments );
        next = local.length >= arity ? fn : resolver;
        return next.apply( null, local );
      };
   }());
}

和小提琴

也可以用Ramda。js这里是Ramda

的用法http://bit.ly/1IfaVM5