美文网首页
Arguments的点点滴滴

Arguments的点点滴滴

作者: Jetsly | 来源:发表于2016-05-18 10:51 被阅读26次

[索引]
[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)是把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数,并且返回接受余下的参数且返回结果的新函数的技术

待续....

相关文章

网友评论

      本文标题:Arguments的点点滴滴

      本文链接:https://www.haomeiwen.com/subject/ooqwrttx.html