简体   繁体   English

块范围如何访问封闭的 scope

[英]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.

相关问题 如何在ECMAScript 5中具有块作用域 - How to have block scopes in ECMAScript 5 为什么我不能在一个“ then”块中访问父级变量,但在下一个块中却可以访问? - Why do I not have access to a parent-scope variable in one “then” block, but I do have access in a subsequent block? 在AngularJS中如何从父范围访问多个子范围 - In AngularJS how to access multiple child scopes from parent scope 无法访问其父作用域的 JS scope - JS scope that cannot access its parents scopes 如何编辑范围? // 谷歌课堂控制谷歌应用脚​​本中学生访问权限范围 - How do I edit scopes? // Google Classroom control permission scopes in google apps scripts for student access 在 Javascript 中,我需要从块作用域访问函数作用域 var,那里已经有同名的 var - In Javascript, I need to access functioned scope var from block scope, I already have var with same name there 如何分离范围而不隔离范围? - how to separate scopes without isolate scope? 如何为函数作用域定义新作用域 - How to define a new scope to a function scopes 当我有嵌套指令时,如何访问特定的父作用域? - How do I get access to a specific parent scope when I have nested directives? JavaScript中的块级范围访问 - Block Level Scope Access In JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM