Javascript:绑定到函数的右边?
如何绑定到函数的右侧?例如:Javascript:绑定到函数的右边?,javascript,functional-programming,Javascript,Functional Programming,如何绑定到函数的右侧?例如: var square = Math.pow.bindRight(2); console.log(square(3)); //desired output: 9 有什么问题吗 var square = function(x) {return x*x;}; 要正确回答此问题,您需要创建一个匿名函数,该函数使用设置的参数调用“绑定”函数,例如: var square = function(x) {return Math.pow(x,2);}; 通过这种方式,可以绑定
var square = Math.pow.bindRight(2);
console.log(square(3)); //desired output: 9
有什么问题吗
var square = function(x) {return x*x;};
要正确回答此问题,您需要创建一个匿名函数,该函数使用设置的参数调用“绑定”函数,例如:
var square = function(x) {return Math.pow(x,2);};
通过这种方式,可以绑定任意数量的参数、重新排列参数或两者的组合。但是,请记住,这会对性能产生一些影响,因为每次像这样绑定时,都会向堆栈中添加额外的函数调用。这似乎需要部分应用程序。有许多库提供了这一功能,包括underline.js:您正在寻找分部函数,这是别名的简写
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
实现您要求的“经典”方式是:
var square = function (x) {
return Math.pow(x, 2);
};
使用部分函数可以:
var square = Math.pow.partial(undefined, 2);
console.log(square(3));
不幸的是,任何浏览器都没有提供Function.prototype.partial
幸运的是,我一直在研究一个我认为是必不可少的JavaScript面向对象的函数、方法、类等的库。
/**
* @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);
};
};
}
}());
/**
*@依赖项
*Array.prototype.slice
*Function.prototype.call
*
*@返回函数
*返回预先填充了提供的参数的curried函数
*/
(功能(){
“严格使用”;
if(!Function.prototype.partial){
Function.prototype.partial=函数(){
var fn,
argmts;
fn=这个;
argmts=参数;
返回函数(){
var arg,
我
args;
args=Array.prototype.slice.call(argmts);
对于(i=arg=0;i
Lodash's将满足您的需求,以下是文档:
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.
此方法类似于u0.partial,只是部分参数
附加到新函数中提供的函数之后。
论据
func(Function):部分应用参数的函数。
[arg](…*):要部分应用的参数。
返回(函数):返回新的部分应用函数。
您可以通过将\uu
作为占位符传递,以便稍后填写:
var square = _.partial(Math.pow, _, 2);
console.log(square(3)); // => 9
此功能出现在2014年2月(下划线)。你的意思是除了他要求其他东西之外吗?那么,我不得不假设这是一个坏例子,因为这个答案非常清楚地解决了所给示例中的问题。所给示例不是要解决的情况,这只是一个例子,你可以理解我需要什么。很抱歉,虽然目的是好的,但这样做不行。请正确回答。希望现在更好。我想Dokkat要求的是bindRight的通用实现。为一个特定的函数编写它是非常简单的。我实际上期望使用标准库或流行库实现它。但似乎没有,所以这是正确的答案。谢谢。我以前没见过这个答案。这实际上是最好的解决办法。谢谢。另请参见下面@brian-m-hunt答案中的lodash
partinankle()
解决方案