currying相关的一个问题,[this].concat([].slice.call(arguments)) 没看懂这个语句?

题目描述

函数asyncify是一个无论异步调用它还是同步调用它,输出结果都相同的函数(本案例中 a = 1),关于同步的那个判断,不太理解其中的逻辑含义, 特别是 [this].concat([].slice.call(arguments)) 这个语句,书中解释说,这个叫currying,后来我查过,大致意思就是可以连续传入参数,后来还是没有看懂这个语句

题目来源及自己的思路

《你不知道的JavaScript(中卷)》的书中“回调”章节的案例

相关代码

function asyncify(fn) {
      var orig_fn = fn,
          intv = setTimeout(function () {
                    intv = null;
                    if (fn) fn();
                 }, 0);
      console.log('Wai intv:'+intv);
      fn = null;
      return function () {
        console.log('Nei intv:'+intv);
        if (intv) {
          // 同步
          fn = orig_fn.bind.apply(
            orig_fn,
            // 把封装器的this添加到bind(..)调用的参数中,
            // 以及克里化(currying)所有传入参数
            [this].concat([].slice.call(arguments))  
          );
        } else {
          // 异步
          orig_fn.apply(this, arguments); 
        }
      };
    }
    function result(data) {
      console.log(a); 
    }

    var a = 0;
    var b = asyncify(result);
    a++;

你期待的结果是什么?实际看到的错误信息又是什么?

返回的结果为 1,实现了书中的要求
阅读 3.2k
3 个回答
 fn = orig_fn.bind.apply(
            orig_fn,
            [this].concat([].slice.call(arguments))  
          );

首先为了实现需求,asyncify(result);创建的新函数的newResult,当然是一次创建一直有用,所以会有orig_fn.bind,而bind的第一个参数当然就是this咯,所以我要的结果就是orig_fn.bind(this,arg1,agr2),那要怎么做呢,自然就是apply了,剩下就没啥了吧。

我猜你是 [].slice.call(arguments) 这里不理解吧
arguments不是真正的数组,需要转换:es5的写法就是[].slice.call(arguments)
ES6的写法:具体可以看阮一峰的ES6

[1].concat([2,3]) 数组连接操作,这个容易明白吧

新手上路,请多包涵

arguments是函数里所有参数的数组集可以用下标访问对应的参数。[].slice.call(arguments)这是argument调用数组的slice方法。 [this].concat([].slice.call(arguments))就是先slice再concat

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题