Javascript:绑定到函数的右侧
Javascript: binding to the right of a function?
如何绑定到函数的右侧?示例:
var square = Math.pow.bindRight(2);
console.log(square(3)); //desired output: 9
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);
};
};
}
}());
Lodash的partialRight
将执行您想要的操作,下面是文档:
这个方法类似于_.partial,除了分部参数被附加到提供给新功能的那些。自变量func(Function):要部分应用参数的函数。[arg](…*):要部分应用的参数。Returns(Function):返回部分应用的新函数。
这似乎需要部分应用程序。有许多库提供了这一功能,包括underscore.js:http://documentcloud.github.com/underscore/
您可以使用undercore.js中的partial
,通过将_
作为占位符传递,以便稍后填写:
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);};
通过这种方式,可以绑定任意数量的参数、重新排列参数或两者的组合。但是,请记住,这会对性能产生一些影响,因为每次像这样绑定时,都会向堆栈添加一个额外的函数调用。
相关文章:
- 如何向onClick事件处理程序传递一个接受参数的函数,并且仍然将该函数绑定到组件's”;这个“;上下文
- Jquery:将函数绑定到已绑定元素的点击事件
- 我可以通过使用函数绑定来保留默认值吗?如果没有,为什么
- 这在 Object 方法中不引用对象,而是引用函数绑定到的标记
- 为什么当我尝试将函数绑定到自身时,“this”对象仍然引用窗口
- 如何将函数绑定到使用链接函数创建 HTML 的角度指令
- 将jquery函数绑定到事件
- 将服务中的函数绑定到$scope(错误:无法设置undefined的属性'onChange')
- 使用闭包/函数绑定将自函数作为回调传递
- 如何在 Javascript 中将函数绑定到对象数据成员的更改
- 需要将内部函数绑定到元素的单击事件
- 在Javascript中将对象原型函数绑定到对象
- 将函数绑定到Twitter Bootstrap Modal Ajax Complete
- ng使用一个不识别临时变量形式ng repeat的函数绑定html
- 将函数绑定到baz后调用fn.apply(bar,[])
- 将函数绑定到采用参数的不同事件
- 如何将返回函数绑定到标记角度
- 在IE9中未检测到视图模型函数绑定,但在FF和Chrome中有效
- 如何将函数绑定到ShadowDOM内部的元素
- 将原型函数绑定到此的方式不那么冗长