簡體   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