loadsh flow用法及源码

用法

function square(n) {
  return n * n;
}
function add(m, n) {
    return m+n;
}

var addSquare = _.flow(add, square);
addSquare(3, 2);
// => 25

如上代码,addSquare(3, 2);会依次执行flow中传入的函数,其中square的参数是add返回的结果;

源码

function flow(...funcs) {
   let len = funcs.length;
   let index = len;
   while(index--) {
       if (typeof funcs[index] !== 'function') {
           throw new TypeError('不是一个函数');
       }
   }
   return function(...args) {
       let index = 0;
       let result = len ? funcs[index].apply(this, args): args[0];
       while (++index < len) {
               result = funcs[index].call(this, result)
           }
       return result;
   }
}

使用apply、call的原因解释,匿名函数中的this指向window,如果没有apply,直接 funcsindex,则add函数的this是funcs数组,显然这个数组对象没有add和square方法,因此会报错

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。

友情链接更多精彩内容