Js因病情而哭泣

问题描述 投票:0回答:1

我试图了解这段代码很长一段时间我知道currying功能但与此代码混淆请解释理论背后

var currying = function(fn) {
  var args = [];
  return function() {
    if (!!arguments.length){
      [].push.apply(args, arguments);
      return arguments.callee;
    } else {
      // what is 'this' in apply method
      return fn.apply(this, args);
    }
  }
} 

// currying var or args
// please explain the code below
var find = function(arr, el){
  return arr.indexOf(el) !== -1;
}

var newFind = currying(find)([1,2,3]);
console.log( newFind(1)());
console.log( newFind(2)());
javascript currying
1个回答
2
投票

为了便于解释,让我们转换代码的最后部分:

// newFind = currying(find)([1,2,3]);
// console.log(newFind(1)());
// above is the same with below
console.log( currying(find)([1,2,3])(1)());

currying采取功能find所以在fncurryingfind。当它返回一个函数时,它可以被调用,因为它显示在代码currying(find)([1,2,3])

让我们来看看这部分,currying(find)([1,2,3])。它执行currying的返回方法。它可以使用关键字arguments访问参数,该关键字是代码中的[1,2,3]数组。

参数是数组,这意味着它具有长度值。然后将参数推入args数组并返回其被调用者,这意味着currying的内部方法。

当它再次返回方法时,可以使用(1)的下一个参数currying(find)([1,2,3])(1)()再次调用它。同样,它使用参数currying执行1的内部方法。然后它不是一个数组,所以它调用fn.apply(this, args)。代码中的this关键字在这种情况下没有任何意义。你可以将this替换为null,或者你可以使用fn(...args)代替。代码用于将argumnts数组转换为每个参数。例如[[1,2,3], 1]转换为[1,2,3], 1然后,最后它执行find函数与参数[1,2,3]1。你应该记住所有这些东西都是来自currying的返回方法所以,你必须把它称为函数。最后追加()来执行该功能。

© www.soinside.com 2019 - 2024. All rights reserved.