js函数柯里化

函数柯里化是什么?

函数柯里化(curry)就是只传递给函数一部分参数来调用它,让它返回一个函数去处理剩下的参数。

函数柯里化案例?

function curry(fn) {
		var args = Array.prototype.slice.call(arguments,1);
		return function(){
			var innerArgs = Array.prototype.slice.call(arguments);
			var finalArgs = args.concat(innerArgs);
			return fn.apply(null, finalArgs);
		}
	}
	
	/*
	程序执行分析:
	1. args = [5];
	2. innerArgs = [3];
	3. finalArgs = [5,3] = [5].concat([3]);
	4. 8
	*/

	function add(num1,num2) {
		return num1+num2;
	}
	//var curriedAdd = curry(add,5);
	alert(curry(add,5)(3));

函数柯里化的应用场景?

最典型的代表应用,是bind函数用以固定this这个易变对象。

Function.prototype.bind = function(context) {
    var _this = this,
    _args = Array.prototype.slice.call(arguments, 1);
    return function() {
        return _this.apply(context, _args.concat(Array.prototype.slice.call(arguments)))
    }
}
posted on 2016-05-26 00:26  DJ荒野  阅读(214)  评论(0编辑  收藏  举报