Arguments的点点滴滴
2016-05-18 本文已影响26人
Jetsly
[索引]
[1.参数转数组]
[2.改变方法的this]
[3.函数柯里化]
1.参数转数组
function log(c){
console.log([].slice.call(arguments));
//console.log(Array.prototype.slice.call(arguments));
}
log('a','c');
输出
['a','c']
2.改变方法的this
function log(){
function _log(c){
console.log(c)
return this;
};
return _log.bind(_log)([].slice.call(arguments)[0]);
// return _log.apply(_log,[].slice.call(arguments).slice(0));
// return _log.call(_log,[].slice.call(arguments)[0]);
}
log('1')('2');
输出
1
2
3.函数柯里化
function add(x,y,z){
return x+y+z;
}
function curryFunc(func){
var args = [];
var len = func.length;;
return function _curryFunc(){
[].push.apply(args, [].slice.apply(arguments));
if(args.length===len){
return func.apply(this,args);
}
return _curryFunc;
}
}
console.log(curryFunc(add)(2,2)(2));
console.log(curryFunc(add)(2)(2)(2));
console.log(curryFunc(add)(2)(2,2));
输出
6
6
6
柯里化(Currying)是把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数,并且返回接受余下的参数且返回结果的新函数的技术
待续....