<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>js柯里化</title>
</head>
<body>
<pre>
把接受多个参数的函数变换成接受一个单一参数的函数,
并且返回接受余下的参数而且返回结果的新函数。
</pre>
<script type="text/javascript">
/* 柯里化函数 */
function currying( fn ){//fn是第一个参数
var proSlice = Array.prototype.slice,
_args = proSlice.call(arguments, 1); //除去第一个参数后,剩余的所有参数;_args: function square(i) {}
return function (){
var __inargs = proSlice.call(arguments);//这里的arguments就是这个匿名函数的所有实参
console.log(__inargs);
return fn.apply(null,_args.concat(__inargs)); //将当前匿名函数的参数与父级函数的参数(除了第一个参数外)合并
};
}
/*
示例一、缩小函数的适用范围,提高函数的适用性
*/
function square(i) {
return i * i;
}
function dubble(i) {
return i*=2;
}
function map(handeler,list){
return list.map(handeler);
}
var mapSQ = currying(map, square);
console.log(mapSQ);
var result = mapSQ([1,2,3,4,5]);
console.log(result);
function Ajax() {
this.xhr = new XMLHttpRequest();
}
/*Ajax.prototype.open = function(type, url , data ,callback){
this.onload = function(){
callback(this.xhr.responseText,this.xhr.status,this.xhr);
}
this.xhr.open(type,url,data.async);
this.xhr.send(data.paras);
}
'get post'.split(' ').forEach(function(mt){
Ajax.prototype[mt] = currying(Ajax.prototype.open,mt);
});*/
/*
示例二、
延迟执行
*/
var curryAdd = function(fn){
var _args = [];
return function cb(){
if(arguments.length == 0){
console.log(this);
return fn.apply(this, _args);
}
if(typeof arguments!="function"){
Array.prototype.push.apply(_args, arguments);
}
return cb;
}
}
function add(){
var ary = arguments,
i = 0,
length = ary.length;
var sum = 0;
for(; i < length; i++){
sum+=ary[i];
}
return sum;
}
//var delaySum = curryAdd(add)(1)(2)(3)();
console.log(delaySum);
var delayFn = curryAdd(add);
delayFn(1);
delayFn(2);
delayFn(3);
delayFn(4);
delayFn();
/* 示例三、固定易变因素 */
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))); } }
/* 示例四、更复杂的"分部"函数 */
Function.prototype.partial = function(){
console.log(this);
var fn = this, //缓存当前的上下文环境(这里一般是某个功能函数)
args = Array.prototype.slice.call(arguments); //得到partial的所有参数 return function(){
var arg = 0;
for(var i = 0;i<args.length && arg < arguments.length; i++){ if(args[i] === undefined){ //如果partial的参数中有遗漏的 args[i] = arguments[arg++];//则用当前匿名函数的参数来填充 }
}
return fn.apply(this, args);
}
}
String.prototype.csv = String.prototype.split.partial(/,\s*/);
var results = ("Mugan, Jin, Fuu").csv();
console.log(results); //["Mugan", "Jin", "Fuu"];
</script>
</body>
</html>