简体   繁体   English

咖喱或关闭

[英]Currying or closure

Hello I'm doing a javascript coding interview, to prepare for an upcoming one.你好,我正在做一个 javascript 编码面试,为即将到来的面试做准备。 i had a question that confused me a bit.我有一个问题让我有点困惑。 The question is as follow :问题如下:

What concept is being illustrated below ?下面说明了什么概念?

function makeAdder(x) {
  return function (y) {
    return x + y;
  };
}

var addFive = makeAdder(5);
console.log(addFive(3));

There were 4 answers to pick from and then there's : Currying and Closure有 4 个答案可供选择,然后是: Currying and Closure

I thought both of these were right.我认为这两个都是对的。 I ended up picking currying, but i really thought this is illustrating closures as well?我最终选择了咖喱,但我真的认为这也说明了闭包? Could you explain why this is not illustrating closures?你能解释一下为什么这不是说明闭包吗?

Currying is always a syntax Sugar for closures.It doesn't call a function.柯里化始终是闭包的语法糖。它不调用函数。 It just transforms it.它只是改变它。

For Your above case It's Just Closures because you are taking another variable which stores inner function and executing differently .对于您的上述情况,这只是闭包,因为您正在使用另一个存储内部函数并以不同方式执行的变量。 Like addFive is inner function which is being invoked later.像 addFive 一样是稍后调用的内部函数。

If you want to to currying it would be like the below example i have created.如果你想柯里化,它就像我创建的下面的例子。 Currying is the concept of closure, due to its leading exection braces which help inner function executions at same times.柯里化是闭包的概念,因为它的前导执行大括号有助于同时执行内部函数。 So here you don't have to take another variable to store for calling the inner function.所以在这里你不必为了调用内部函数而存储另一个变量。

By definition, currying should convert sum(a, b, c) into sum(a)(b)(c).根据定义,柯里化应该将 sum(a, b, c) 转换为 sum(a)(b)(c)。

 function makeAdder(x) { return function (y) { return x + y; }; } console.log(makeAdder(5)(3));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM