JavaScript Closure: Returning a Function

本秂侑毒 提交于 2019-12-23 01:41:56

问题


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));

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?


回答1:


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];
}

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.

To make it clear, see this:




回答2:


Theres a self calling, anonymous function (function(){})() . So digit_name is not the function, its what the function outputs in is return statement.So this happens inside the browser:

var digit_name=(function(){})();
var digit_name=function(n){}



回答3:


The outer function is an IIFE, an immediately-invoked function expression. That function is ran when the script starts and therefore the inner function returned by the IIFE is what is assigned to digit_name.

The "magic" of the closure if that this inner function still has access to everything in the closure (such as the names array).

https://developer.mozilla.org/en-US/docs/Glossary/IIFE



来源:https://stackoverflow.com/questions/38875221/javascript-closure-returning-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!