[英]How do block scopes have access to enclosing scope
i do understand that due to lexical scoping, block scopes can access the enclosing scope variables.我确实明白,由于词法作用域,块作用域可以访问封闭的 scope 变量。 But what i do not understand is how it really works.但我不明白的是它是如何工作的。 ex:前任:
function first(){
let i=10;
function second(){
let j=20;
console.log(i);
if(j==20){
console.log(i);
}
}
second();
}
the first console.log() get the value of i after its looks up the scope chain in the variable object. But how does the console.log() inside the block get access to variable i as it does not create an execution context and thus no scope chain.第一个 console.log() 在查找变量 object 中的 scope 链后获得 i 的值。但是块内的 console.log() 如何访问变量 i 因为它不创建执行上下文并且因此没有 scope 链。
js engine stores hoisted ( by hoisting ) variable and function declarations to the top of particular scope in which that variable or function is declared. js 引擎将提升(通过提升)变量和 function 声明存储到特定 scope 的顶部,其中声明了该变量或 function。 Assignment operations aren't hoisted.不会提升分配操作。 So engine knows in which scope variable or function is declared.所以引擎知道在哪个 scope 变量或 function 中声明。
https://medium.com/@venomnert/how-js-engine-reads-your-code-df3cd36e4192 https://medium.com/@venomnert/how-js-engine-reads-your-code-df3cd36e4192
above article describes how js engine finds variables and some other concepts which can be helpful to understand closures and execution of code.上面的文章描述了 js 引擎如何找到变量和其他一些有助于理解闭包和代码执行的概念。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.