Javascript:sum(2)(3)的含义是什么//返回5; [英] Javascript:What is meaning of sum(2)(3) //returns 5;

查看:746
本文介绍了Javascript:sum(2)(3)的含义是什么//返回5;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码打击以返回它的值。

Here is code blow to return it's value.

function sum(a){
  return function(b){
    return a+b;
  }
}
sum(2)(3);

它返回5但如果我输入代码:

It returns 5 but if I type code:

function sum(a){
  function add(b){
    return a+b;
  }
return add(b);
}

它没有返回预期值5.我甚至不明白 sum(2)(3)调用函数。对此有任何解释。非常感谢。

It doesn't return expected value 5. I don't even understand how sum(2)(3) calls function. Any explanation for this is very much appreciated.

推荐答案

这称为关闭

sum( a)返回一个带有一个参数 b 的函数,并将其添加到 a 。可以这样想:

sum(a) returns a function that takes one parameter, b, and adds it to a. Think of it like this:

   sum(2)(3);

   // Is equivalent to...
   function add(b){
       return 2+b;
   }
   add(3);

   // Which becomes...
   return 2+3; // 5

您的第二个代码段不起作用,因为您尝试引用 b 来自外部函数,但只有内部函数有任何 b 的概念。你想改变这个:

Your second snippet doesn't work because you're trying to reference b from the outer function, but only the inner function has any notion of what b is. You want to change this:

function sum(a){
  function add(b){
    return a+b;
  }
  return add(b);
}

到此:

function sum(a){
  function add(b){
    return a+b;
  }
  return add; // Return the function itself, not its return value.
}

当然,这相当于第一个片段。

Which is, of course, equivalent to the first snippet.

这篇关于Javascript:sum(2)(3)的含义是什么//返回5;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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