2012-03-20 26 views

回答

6

您正在寻找部分函数,​​这些函数是别名方便的简写。

“经典”的方式做你问的是:

var square = function (x) { 
    return Math.pow(x, 2); 
}; 

使用部分功能,这将是:

var square = Math.pow.partial(undefined, 2); 
console.log(square(3)); 

不幸的是,Function.prototype.partial不提供任何浏览器。


幸运的是,我一直在努力的东西,我认为是必要的的JavaScript面向对象的功能,方法,类等等,这是Function.prototype.partial.js库:

/** 
* @dependencies 
* Array.prototype.slice 
* Function.prototype.call 
* 
* @return Function 
* returns the curried function with the provided arguments pre-populated 
*/ 
(function() { 
    "use strict"; 
    if (!Function.prototype.partial) { 
     Function.prototype.partial = function() { 
      var fn, 
       argmts; 
      fn = this; 
      argmts = arguments; 
      return function() { 
       var arg, 
        i, 
        args; 
       args = Array.prototype.slice.call(argmts); 
       for (i = arg = 0; i < args.length && arg < arguments.length; i++) { 
        if (typeof args[i] === 'undefined') { 
         args[i] = arguments[arg++]; 
        } 
       } 
       return fn.apply(this, args); 
      }; 
     }; 
    } 
}()); 
+0

我以前没有见过这个答案。这实际上是最好的解决方案。谢谢。 – MaiaVictor 2012-04-10 18:08:29

+0

另请参阅在@ brian-m-hunt中回答lodash下的partialRight()解答 – Offirmo 2016-05-09 10:23:03

-1

出了什么问题:

var square = function(x) {return x*x;}; 

要正确地回答这个问题,你需要创建一组参数调用“绑定”功能的匿名功能,如:

var square = function(x) {return Math.pow(x,2);}; 

以这种方式,您可以绑定任意数量的参数,重新排列参数或两者的组合。但是请记住,这会对性能产生一些影响,因为每当你这样绑定时,你都会向堆栈添加一个额外的函数调用。

+1

你的意思是除了他要求别的东西吗? – gdoron 2012-03-20 21:20:20

+0

然后,我将不得不假设这是一个不好的例子,因为这个答案很清楚地解决了给出的例子中的问题。 – 2012-03-20 21:21:01

+4

给出的例子并不是要解决的问题,它只是一个例子,所以你可以理解我需要什么。对不起,但这不会做到,尽管意图是好的。 – MaiaVictor 2012-03-20 21:22:27

11
Function.prototype.bindRight = function() { 
    var self = this, args = [].slice.call(arguments); 
    return function() { 
     return self.apply(this, [].slice.call(arguments).concat(args)); 
    }; 
}; 

var square = Math.pow.bindRight(2); 
square(3); //9 
+0

我实际上期待使用标准库或流行库的实现。但似乎没有,所以这是正确的答案。谢谢。 – MaiaVictor 2012-03-20 21:45:03

3

Lodash的partialRight会做你想要什么,这里是文档:

 
This method is like _.partial except that partial arguments 
are appended to those provided to the new function. 

Arguments 
     func (Function): The function to partially apply arguments to. 
     [arg] (…*)  : Arguments to be partially applied. 
Returns  (Function): Returns the new partially applied function. 
0

你可以用012做,通过传递_作为占位符,稍后填写的:

var square = _.partial(Math.pow, _, 2); 
console.log(square(3)); // => 9 

这项功能出现在2014年2月(下划线1.6.0)。