繁体   English   中英

Javascript:为什么我可以访问全局范围内的函数内声明的内部名称?

[英]Javascript: why can I access the inner name declared inside a function in global scope?

在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

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

提前致谢!

没有变量var在全球范围内产生。

在执行赋值时,将值分配给未声明的变量会隐式地将其创建为全局变量(它成为全局对象的属性)。

您尚未使用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();
  };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM