JavaScript中的咖喱函数使用闭包原则吗? [英] Does curry function in javascript uses principle of closure?

查看:94
本文介绍了JavaScript中的咖喱函数使用闭包原则吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有人解释咖喱功能的作用,这将是非常有帮助的。我已经阅读了很多例子,但无法正确掌握它。它是否与关闭有关。

解决方案

柯里里只是一种技巧,可以利用任何语言特性(例如闭包)来达到理想的结果,但它没有定义必须使用哪种语言功能。因为咖喱并不需要使用关闭(但在大多数情况下会关闭)



这里是一个使用柯里化的小例子,用没有使用闭包。



使用闭包:

 函数addition(x,y){
if(typeof y ===undefined){
return function(y){
return x + y;
}
}
return x + y;
}

var additionRemaining = addition(3); // Currying
additionRemaining(5); //添加5到3

新函数而不是闭包(部分计算):

 函数加法(x,y){
if(typeof y ===undefined){
return new Function('y','return'+ x +'+ y;');
}
return x + y;
}

var additionRemaining = addition(3); // Currying
additionRemaining(5); // add 5 to 3


It would be very helpful, if someone explains the working of a curry function. I have read many examples, but not able to grasp it properly. Is it anyhow related to closure.

解决方案

Currying is just technique, that can make use of any language feature (e.g. closures) to achieve the desired result, but it is not defined what language feature has to be used. As of that currying does not require to make use of closures (but in most of the cases closures will be used)

Here a little example of the usage of currying, with and without the usage of closure.

With the use closure:

function addition(x,y) {
  if (typeof y === "undefined" ) {
    return function (y) {
      return x + y;
    }
  }
  return x + y;
}

var additionRemaining = addition(3); // Currying
additionRemaining(5);//add 5 to 3

With the use of new Function instead of closure (partial evaluation):

function addition(x,y) {
  if (typeof y === "undefined" ) {
    return new Function('y','return '+x+' + y;');
  }
  return x + y;
}

var additionRemaining = addition(3); // Currying
additionRemaining(5);//add 5 to 3

这篇关于JavaScript中的咖喱函数使用闭包原则吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆