【问题标题】:Javascript: why can I access the inner name declared inside a function in global scope?Javascript:为什么我可以访问在全局范围内的函数内声明的内部名称?
【发布时间】:2017-01-18 15:30:18
【问题描述】:

在 chrome 开发控制台中, 我创建了一个函数 f 和另外两个嵌入函数

> var a = 'ga';
  var b = 'gb';
  var c = 'gc';
  var f = function(){
      var a = 'fa';
      var b = 'fb';
      ff = function(){
          var a = 'ffa';
          fff = function(){
              console.log("a,b,c is: " + a + "," + b + "," + c);
          };
          fff();
      };
      ff();
  };
< undefined

然后,我在控制台输入ff,发现还是可以访问的, 而它是在f的内部范围内定义的

> ff     // why can I still access the name ff ?
< function (){
         var a = 'ffa';
         fff = function(){
             console.log("a,b,c is: " + a + "," + b + "," + c);
         };
         fff();
     }

fff这个名字也是如此

> fff   // why can I still access the name fff ?
< function (){
             console.log("a,b,c is: " + a + "," + b + "," + c);
         }

我是一名 C/C++ 开发人员,目前正在学习 javascript。

这种现象对我来说似乎很难理解。
因为在 Cpp 中,访问内部范围内的名称是错误的。
例如:

#include <iostream>

using namespace std;

int main(int argc, char *argv[]){
    auto f = [](){
        std::cout << "in f() now" << std::endl;
        auto ff = [](){
            std::cout << "in ff() now" << std::endl;
            auto fff = [](){
                std::cout << "in fff() now" << std::endl;
            };
            fff();
        };
        ff();
    };

    f(); //it's okay
    ff(); // not okay, error: use of undeclared identifier 'ff'
    fff(); // not okay too, error: use of undeclared identifier 'fff'

    return 0;
}

即使在 python 中,我们也不能这样做:

def f():
    print("in f() now")
    def ff():
        print("in ff() now")
        def fff():
            print("in fff() now")
        fff()
    ff()

f()   # okay
ff()  # NameError: name 'ff' is not defined
fff() # NameError: name 'fff' is not defined

所以,我想知道为什么即使我不在其范围内,也可以在内部范围内访问名称

提前致谢!

【问题讨论】:

  • 因为 JS 就是这样设计的。如果没有使用 var/const/let 的声明,它将分配给全局变量。

标签: javascript scope closures


【解决方案1】:

没有var 的变量是在全局上下文中生成的。

给一个未声明的变量赋值会在赋值执行时隐式地把它创建为一个全局变量(它成为全局对象的一个​​属性)。

【讨论】:

  • 著名例子for(i = 0; i &lt; ....
【解决方案2】:

您尚未使用var 声明fffff。如果您不声明它们,它们会自动在全局而非本地声明。

所以我没有尝试过,但这应该更像你所追求的......

  var a = 'ga';
  var b = 'gb';
  var c = 'gc';
  var f = function(){
      var a = 'fa';
      var b = 'fb';
      var ff = function(){
          var a = 'ffa';
          var fff = function(){
              console.log("a,b,c is: " + a + "," + b + "," + c);
          };
          fff();
      };
      ff();
  };

【讨论】:

  • 对不起,让我等了 3 分钟。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-01
  • 1970-01-01
  • 2017-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多