javascript - JS - 在外部函数之外声明嵌套函数

标签 javascript function lexical-scope

案例 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. When bar 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/

相关文章:

javascript - 需要在页脚上方停止我的固定侧边栏

javascript - 在 Javascript 中解析 ISO 8601 时间间隔

Javascript:for语句不处理数组中的所有元素

javascript - Socket.IO 服务器性能和带宽使用

javascript - 为什么代码片段会这样输出?

r - 如何使用 purrr::pmap 从数据框设置函数参数而不写所有的列名?

c - 递归函数怎么会返回一些东西?

python - 是否可以使用逻辑语句作为参数来调用python函数?

javascript - 什么是词法作用域?

perl - 我的 $_;如果 $_ 是隐含的,则做任何事情