简体   繁体   English

Javascript中的作用域链,并在全局作用域中调用嵌套函数

[英]Scope chain in Javascript and calling nested function within the global scope

Here is the example I want to be enlighten on (Something that doesn't actually works). 这是我想启发的示例(实际上不起作用的某些东西)。

 var myVar = 2;

    function a(){
     var myVar = 2;
        function b(){
            console.log(myVar);
        }
    };
   a();
   b();

This will output in the console: Uncaught ReferenceError: b is not defined. 这将在控制台中输出:Uncaught ReferenceError:未定义b。

As you can see I have a function named a with a nested function called b . 如您所见,我有一个名为a的函数,以及一个名为b的嵌套函数。

At first I thought I could invoke b outside a and get it working normally. 起初,我以为我可以调用31b的外侧得到它正常工作。 I thought that would work because at first I call the a function. 我认为这会起作用,因为首先我将其称为a函数。

By doing that I had in mind the fact that the a function would be put on the execution stack and during its creation phase the b function defined inside would be set in the memory. 通过这样做,我想到了一个事实, 一个a函数将被放置在执行堆栈上,而在其创建阶段,将在内存中设置内部定义的b函数

As this is in memory I thought I could then execute this outside the function. 由于这是在内存中,所以我认为我可以在函数之外执行此操作。 Which obviously doesn't work. 这显然是行不通的。

So my conclusion is the b function is indeed set into memory during the creation phase of the a function but once the a function has finished to execute, once it's popped of the execution stack, the b function gets popped off the memory at the same time. 所以我的结论是在一个函数的创建阶段的B功能确实设置到内存中,但一旦一个函数完成执行,一旦它的弹出执行堆栈中,B功能被同时弹出内存。

Thus calling it (I mean the b function) within the global scope is impossible. 因此,不可能在全局范围内调用它(我的意思是b函数)。

Am I right on this ? 我对吗?

You are complicating things unnecessarily by speaking about execution stacks, creation phases and such. 通过谈论执行栈,创建阶段等,您不必要地使事情复杂化。

The explanation is very simple: you cannot call b because the spec says that b is out of scope at the site where you are trying to call it. 解释非常简单:您不能调用b因为规范指出b在您尝试对其进行调用的站点之外。 That is all, end of story. 仅此而已,故事的结局。

Your example would actually work if converted to PHP, which makes me think that perhaps this is where you got the idea from. 如果将您的示例转换为PHP,则实际上可以正常工作,这使我认为这也许是您从中获得灵感的地方。 But JS and PHP are different languages and the (IMO ridiculous) manner that PHP treats nested functions does not transfer over. 但是JS和PHP是不同的语言,PHP对待嵌套函数的(IMO荒谬)方式不会转移。

If you want to call b outside of a , you need to create a reference to it outside of a : 如果你想调用b以外的a ,你需要创建外部对它的引用a

var myVar = 2;

function a(){
  var myVar = 2;
  function b(){
      console.log(myVar);
  }
  return b;
};

var b = a();
b();

This however won't cause b to print the global myVar . 但是,这不会导致b打印全局myVar It will still have access to the myVar inside the closure scope of a . 它仍然可以访问myVar关闭范围内的a

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

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