Javascript社区。
Anthony Alicea的课程名为“理解奇怪的部分”(ECMAScript 5),第2节,视频16:作用域链,我想我发现JS解释器如何使用作用域链执行函数存在不一致之处。
我知道Javascript中的每件事都发生在它自己的执行上下文中,全局函数被创建,然后每个函数被创建、执行、放在堆栈上、从堆栈中取出等等。我明白了。
然而,我不理解当一个函数被放到与全局上下文相同级别的执行堆栈上时的作用域链,为什么它不将变量的值的作用域放在外部和全局上下文中,而是将其console.log为未定义的。
请看下面的代码作为示例:
//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”关键字时为ECMAScript 5提供注释,而不是最新的“let”或“const”构造。
感谢您的所有回复!
发布于 2021-06-27 11:08:26
控制台会生成一个未定义的,因为变量尚未定义。JavaScript直到执行完函数b()后才读取变量定义。
https://stackoverflow.com/questions/60644526
复制相似问题