【发布时间】:2012-04-05 09:50:48
【问题描述】:
如何绑定到函数的右侧?示例:
var square = Math.pow.bindRight(2);
console.log(square(3)); //desired output: 9
【问题讨论】:
标签: javascript functional-programming
如何绑定到函数的右侧?示例:
var square = Math.pow.bindRight(2);
console.log(square(3)); //desired output: 9
【问题讨论】:
标签: javascript functional-programming
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 面向对象的函数、方法、类等的库。这是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);
};
};
}
}());
【讨论】:
partialRight() 解决方案
Lodash 的 partialRight 会做你想做的事,这里是文档:
【讨论】:
这似乎你想要部分应用。有许多库提供了该功能,包括 underscore.js:http://documentcloud.github.com/underscore/
【讨论】:
您可以使用partial from underscore.js 来完成,通过传递_ 作为占位符,稍后填写:
var square = _.partial(Math.pow, _, 2);
console.log(square(3)); // => 9
此功能于 2014 年 2 月出现(下划线 1.6.0)。
【讨论】:
有什么问题:
var square = function(x) {return x*x;};
要正确回答问题,需要创建一个匿名函数,调用带有设置参数的“绑定”函数,如:
var square = function(x) {return Math.pow(x,2);};
通过这种方式,您可以绑定任意数量的参数、重新排列参数或两者的组合。但是请记住,这会对性能产生一些影响,因为每次像这样绑定时都会向堆栈添加额外的函数调用。
【讨论】: