JavaScript关闭:返回一个函数 [英] JavaScript Closure: Returning a Function

查看:89
本文介绍了JavaScript关闭:返回一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过Douglas Crockford的JavaScript系列讲座。我对他所展示的代码示例感到困惑,以说明'封闭':

I am working my way through a JavaScript lecture series by Douglas Crockford. I am confused by a code example he is showing to illustrate 'closure':

var digit_name = (function () {
  var names = ['zero', 'one', 'two', 'three'];
  
  return function (n) {
    return names[n];
  };
  
}());

alert(digit_name(3));

如何/为何可以 digit_name 在定义中没有指定参数(最外面的函数)时接受参数?在调用期间,参数(在本例中为 3 )如何知道内部函数定义中的 n ? / p>

How/why can digit_name take an argument when no parameter is specified in the definition (the outermost function)? How does the argument (in this case 3) know to correspond to n within the inner function definition during invocation?

推荐答案

digit_name 存储内部函数返回由外部函数编辑,这是立即执行的函数表达式,其中内部函数具有带有一个参数的签名,而这是存储在 digit_name 。

The digit_name stores the inner function returned by the outer function, which is an Immediately Executed Function Expression, where the inner function has the signature with one parameter and that's what is stored in the digit_name.

function (n) {
  return names[n];
}

最终,以上将是 digit_name 名称是一个私有变量,它与 digit_name 的环境捆绑在一起。私有变量的概念只能使用闭包。

Ultimately, the above will be the digit_name and the names is a private variable, which is bundled with the environment of digit_name. The concept of private variable is possible only using closures.

为清楚起见,请参阅:

< a href =https://i.stack.imgur.com/7i4LL.png =nofollow noreferrer>

这篇关于JavaScript关闭:返回一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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