简体   繁体   English

无法理解JavaScript中的词法范围

[英]Having troubles understanding lexical scope in javascript

I'm reading some books, learning javascript, and i see that javascript uses lexical scope. 我正在看书,学习javascript,并且看到javascript使用了词法作用域。

Lexical scoping means whatever variables are in scope where you define a function from (as opposed to when you call it) are in scope in the function 词法作用域意味着您在其中定义函数的范围内的任何变量(与调用时相反)都在函数的范围内

I tried some basic example: 我尝试了一些基本示例:

function f() {
  console.log(x);
}
const x = 10;
f(); // 10

Then how does this work, and why does it log value 10? 那么这是如何工作的,为什么它会记录值10? Variable x doesn't exist when I define the function. 定义函数时,变量x不存在。 I'm javascript noob, so maybe I'm missing something here. 我是javascript noob,所以也许我在这里错过了一些东西。 Thanks in advance. 提前致谢。

This is due to a concept named Hoisting. 这是由于名为提升的概念。 Essentially, any declaration is moved to the top of the scope, and hence is always accessible anywhere in the scope. 本质上,任何声明都移至范围的顶部,因此始终可以在范围的任何位置访问。

During the time your function id being defined, a lexical scope captures the reference to x. 在定义函数id的过程中,词法范围捕获对x的引用。

Post which x is assigned 10. 发布了x的帖子10。

Read more about hoisting in JS here. 在此处阅读有关JS吊装的更多信息。 (JavaScriptisSexy.com) More specifically about Hoisting and const here. (JavaScriptisSexy.com) 在此处更具体地讲到提升和const。

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

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