| 
                         偏函数应用:一个过程,它传给某个函数其中一部分参数,然后返回一个新的函数,该函数等待接受后续参数。换句话说,偏函数应用是一个函数,它接受另一个函数为参数,这个作为参数的函数本身接受多个参数,它返回一个函数,这个函数与它的参数函数相比,接受更少的参数。偏函数应用提前赋予一部分参数,而返回的函数则等待调用时传入剩余的参数。 
偏函数应用通过闭包作用域来提前赋予参数。你可以实现一个通用的函数来赋予指定的函数部分参数,它看起来如下: 
- partialApply(targetFunction: Function, ...fixedArgs: Any[]) => 
 -  functionWithFewerParams(...remainingArgs: Any[]) 
 
  
如果你要更进一步理解上面的形式,你可以看这里。 
partialApply 接受一个多参数的函数,以及一串我们想要提前赋给这个函数的参数,它返回一个新的函数,这个函数将接受剩余的参数。 
下面给一个例子来说明,假设你有一个函数,求两个数的和: 
- const add = (a, b) => a + b; 
 
  
现在你想要得到一个函数,它能够对任何传给它的参数都加 10,我们可以将它命名为 add10()。add10(5) 的结果应该是 15。我们的  partialApply() 函数可以做到这个: 
- const add10 = partialApply(add, 10); 
 - add10(5); 
 
  
在这个例子里,参数 10 通过闭包作用域被提前赋予 add(),从而让我们获得 add10()。 
现在让我们看一下如何实现 partialApply(): 
- // Generic Partial Application Function 
 - // https://jsbin.com/biyupu/edit?html,js,output 
 - // https://gist.github.com/ericelliott/f0a8fd662111ea2f569e 
 - // partialApply(targetFunction: Function, ...fixedArgs: Any[]) => 
 - // functionWithFewerParams(...remainingArgs: Any[]) 
 - const partialApply = (fn, ...fixedArgs) => { 
 -  return function (...remainingArgs) { 
 -  return fn.apply(this, fixedArgs.concat(remainingArgs)); 
 -  }; 
 - }; 
 - test('add10', assert => { 
 -  const msg = 'partialApply() should partially apply functions' 
 -  const add = (a, b) => a + b; 
 -  const add10 = partialApply(add, 10); 
 -  const actual = add10(5); 
 -  const expected = 15; 
 -  assert.equal(actual, expected, msg); 
 - }); 
 
  
如你所见,它只是简单地返回一个函数,这个函数通过闭包访问了传给 partialApply() 函数的 fixedArgs 参数。 
轮到你来试试了 
你用闭包来做什么?如果你有最喜欢的应用场景,举一些例子,在评论中告诉我。 
                         (编辑:滁州站长网) 
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! 
                     |