JavaScript Closure: Returning a Function

爱⌒轻易说出口 提交于 2019-12-08 18:23:26

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:

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){}

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

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