【发布时间】:2018-09-17 18:09:59
【问题描述】:
在函数 outer 中,我返回一个函数,该函数使用与在 outer 中声明/定义的变量同名。
那么为什么没有创建闭包呢?为什么下面的代码打印的是undefined,而不是Yolo!?
function inner(){
console.log('theVar', theVar);
}
function outer(){
var theVar = 'Yolo!';
return inner;
}
console.log('Starting...');
outer()();
【问题讨论】:
-
因为
theVar不在inner()的范围内。您从outer返回函数引用的事实与inner有权访问的内容无关。 -
因为你还没有定义
innerinsideouter。 jsfiddle.net/khrismuc/upchb9dv -
在函数被声明(见developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…)的地方创建了一个闭包,而不是在它被分配的所有地方
-
阅读您自己添加的
lexical-scope标签的文本。出于某种原因,它们被称为 lexical 闭包。 -
function a() { var x = 5; } function b() { console.log(x); } a(); b()- 你会期望这些记录值5只是因为变量具有相同的名称?不,var x声明了一个 local 变量
标签: javascript scope closures lexical-scope