首页 > 解决方案 > 关于学习 Javascript、执行上下文、堆栈、闭包的基本问题

问题描述

Javascript 社区。

Anthony Alicea 的课程名为“Understanding The Weird Parts”(ECMAScript 5),第 2 节,视频 16:作用域链,我想我发现 JS 解释器使用作用域链执行函数的方式不一致。

我知道 Javascript 中的所有内容都发生在它自己的执行上下文中,创建全局,然后创建执行每个函数,放置在堆栈上,从堆栈中取出等等。我明白了。

但是,当一个函数被放置到与全局上下文相同级别的执行堆栈上时,我不理解作用域链,为什么它不会在全局上下文中作用域来获取变量的值,而是将其控制台记录为未定义.

请以以下代码为例:

//Following function is created within the global execution context
function a3() {
    console.log(myVar3);  //The console.log generates a 'undefined' here, why not a 1? 
    function b3(){
        console.log(myVar3); //console.log generates a 2, because it follows the scope chain
                             //and looks outside of its execution context; why does function a3
                             //not do this with the global context?
    }
    var myVar3 = 2;
    b3();

}
var myVar3 = 1; // Global execution context
a3();           // Global execution context

为什么函数 a3 中的 console.log 不查看全局执行上下文并为值打印 1?它似乎与 a3 到 b3 中的函数调用的相同模式不一致。b3 函数中的 myVar3 超出其执行上下文并找到值 2。

请有人能解释为什么不一致的治疗?

在学习最新的 ECMAScript 功能之前,我试图获得良好的基本理解。请仅在使用 'var' 关键字而不是最新的 'let' 或 'const' 构造时提供 ECMAScript 5 的注释。

感谢您的所有回复!

标签: javascriptscopeclosuresexecutioncontext

解决方案


控制台生成未定义,因为该变量尚未定义。JavaScript 在执行函数 b() 之前不会读取变量定义。


推荐阅读