案例 1:我明白为什么它在这种情况下有效:
function foo(arg) {
var outer = " this is the outer variable";
function bar() {
console.log("arg: " + arg);
console.log("outer variable: ", outer);
}
bar();
}
console.log(foo("hello"));
情况2:但我不明白为什么如果在外部单独声明bar
函数,以下代码不起作用:
function foo(arg) {
var outer = " this is the outer variable";
bar();
}
function bar() {
console.log("arg: " + arg);
console.log("outer variable: ", outer);
}
console.log(foo("hello"));
情况 3:如果我向 bar
函数添加参数:
function foo(arg) {
var outer = " this is the outer variable";
bar();
}
function bar(arg, outer) {
console.log("arg: " + arg);
console.log("outer variable: ", outer);
}
console.log(foo("hello"));
输出:
"arg: undefined"
"outer variable: " undefined
我的问题是关于情况 2:为什么 bar()
无法到达 foo()
中定义的变量?
编辑案例2:
从所有反馈中了解到,我已向 bar(arg, external)
添加了参数,并且它有效。非常感谢。
function foo(arg) {
var outer = " this is the outer variable";
bar(arg, outer);
}
function bar(arg, outer) {
console.log("arg: " + arg);
console.log("outer variable: ", outer);
}
console.log(foo("hello"));
它有效。
最佳答案
When
bar
is defined, its scope chain is created, preloaded with the global variable object, and saved to the internal[[Scope]]
property. Whenbar
is called, an execution context is created and its scope chain is built up by copying the objects in the function’s [[Scope]] property
所以,如果你给 bar
两个参数 arg,outer
,那就行了:
function foo(arg) {
var outer = " this is the outer variable";
bar();
}
function bar(arg,outer) {
console.log("arg: " + arg);
console.log("outer variable: ", outer);
}
console.log(foo("hello"));
Professional JavaScript for Web Developers.3rd.Edition.Jan.2012
p222
关于javascript - JS - 在外部函数之外声明嵌套函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48742705/