Home >Web Front-end >JS Tutorial >Detailed explanation of scope and scope chain in JavaScript
JavaScript has a feature called scope. Although the concept of scope is not easy to understand for many novice developers, in this article I will try my best to explain scope and scope chain in the simplest way possible. I hope everyone will learn something!
Scope is a variable in some specific part of the runtime code , accessibility of functions and objects. In other words, scope determines the visibility of variables and other resources within a block of code. Maybe these two sentences are not easy to understand. Let's take a look at an example first:
function outFun2() { var inVariable = "内层变量2"; } outFun2();//要先执行这个函数,否则根本不知道里面是啥 console.log(inVariable); // Uncaught ReferenceError: inVariable is not defined
From the above example, you can understand the concept of scope. The variable inVariable is not declared in the global scope, so it is in the global scope. An error will be reported if the value is retrieved. We can understand it this way: The scope is an independent territory, so that the variables will not be leaked or exposed. In other words, the biggest use of scope is to isolate variables. Variables with the same name in different scopes will not conflict.
Before ES6, JavaScript did not have block-level scope, only global scope and function scope. The arrival of ES6 provides us with ‘block-level scope’, which can be reflected by the new commands let and const.
Objects that can be accessed anywhere in the code have global scope. Generally speaking, the following situations Have global scope:
var outVariable = "我是最外层变量"; //最外层变量 function outFun() { //最外层函数 var inVariable = "内层变量"; function innerFun() { //内层函数 console.log(inVariable); } innerFun(); } console.log(outVariable); //我是最外层变量 outFun(); //内层变量 console.log(inVariable); //inVariable is not defined innerFun(); //innerFun is not defined
function outFun2() { variable = "未定义直接赋值的变量"; var inVariable2 = "内层变量2"; } outFun2();//要先执行这个函数,否则根本不知道里面是啥 console.log(variable); //未定义直接赋值的变量 console.log(inVariable2); //inVariable2 is not defined
Generally, the built-in properties of window objects are Have global scope, such as window.name, window.location, window.top, etc.
The global scope has a drawback: if we write many lines of JS code and the variable definitions are not included in functions, then they will all be in the global scope. This will pollute the global namespace and easily cause naming conflicts.
// 张三写的代码中 var data = {a: 100} // 李四写的代码中 var data = {x: true}
This is why the source code of libraries such as jQuery and Zepto will be placed in (function(){....})()
. Because all variables placed inside will not be leaked or exposed, will not be polluted to the outside, and will not affect other libraries or JS scripts. This is a manifestation of function scope.
Function scope refers to variables declared inside a function. Contrary to the global scope, the local scope is generally only accessible within a fixed code fragment, most commonly within a function.
function doSomething(){ var blogName="浪里行舟"; function innerSay(){ alert(blogName); } innerSay(); } alert(blogName); //脚本错误 innerSay(); //脚本错误
Scopes are hierarchical. The inner scope can access variables in the outer scope, but not vice versa. Let’s look at an example. It may be easier to understand using bubbles as a metaphor for scope:
The final output result is 2, 4, 12
It is worth noting: Block statements (statements between curly brackets "{}"), such as if and switch conditional statements or for and while loop statements, unlike functions, they do not A new scope will be created. Variables defined within a block statement will remain in the scope in which they already exist.
if (true) { // 'if' 条件语句块不会创建一个新的作用域 var name = 'Hammad'; // name 依然在全局作用域中 } console.log(name); // logs 'Hammad'
Beginners to JS often need some time to get used to variable hoisting, and if they don't understand this unique behavior, it may lead to
bugs. Because of this, ES6 introduced block-level scope to make the life cycle of variables more controllable.
Block-level scope can be declared through the new commands let and const. The declared variables cannot be declared outside the scope of the specified block. access. Block-level scope is created in the following situations:
function getValue(condition) { if (condition) { let value = "blue"; return value; } else { // value 在此处不可用 return null; } // value 在此处不可用 }
var count = 30; let count = 40; // Uncaught SyntaxError: Identifier 'count' has already been declared
在本例中, count 变量被声明了两次:一次使用 var ,另一次使用 let 。因为 let 不能在同一作用域内重复声明一个已有标识符,此处的 let 声明就会抛出错误。但如果在嵌套的作用域内使用 let 声明一个同名的新变量,则不会抛出错误。
var count = 30; // 不会抛出错误 if (condition) { let count = 40; // 其他代码 }
开发者可能最希望实现 for 循环的块级作用域了,因为可以把声明的计数器变量限制在循环内,例如,以下代码在 JS 经常见到:
<button>测试1</button> <button>测试2</button> <button>测试3</button> <script type="text/javascript"> var btns = document.getElementsByTagName('button') for (var i = 0; i < btns.length; i++) { btns[i].onclick = function () { console.log('第' + (i + 1) + '个') } } </script>
我们要实现这样的一个需求: 点击某个按钮, 提示"点击的是第 n 个按钮",此处我们先不考虑事件代理,万万没想到,点击任意一个按钮,后台都是弹出“第四个”,这是因为 i 是全局变量,执行到点击事件时,此时 i 的值为 3。那该如何修改,最简单的是用 let 声明 i
for (let i = 0; i < btns.length; i++) { btns[i].onclick = function () { console.log('第' + (i + 1) + '个') } }
首先认识一下什么叫做 自由变量 。如下代码中,console.log(a)
要得到 a 变量,但是在当前的作用域中没有定义 a(可对比一下 b)。当前作用域没有定义的变量,这成为 自由变量 。自由变量的值如何得到 —— 向父级作用域寻找(注意:这种说法并不严谨,下文会重点解释)。
var a = 100 function fn() { var b = 200 console.log(a) // 这里的a在这里就是一个自由变量 console.log(b) } fn()
如果父级也没呢?再一层一层向上寻找,直到找到全局作用域还是没找到,就宣布放弃。这种一层一层的关系,就是 作用域链 。
var a = 100 function F1() { var b = 200 function F2() { var c = 300 console.log(a) // 自由变量,顺作用域链向父作用域找 console.log(b) // 自由变量,顺作用域链向父作用域找 console.log(c) // 本作用域的变量 } F2() } F1()
关于自由变量的值,上文提到要到父作用域中取,其实有时候这种解释会产生歧义。
var x = 10 function fn() { console.log(x) } function show(f) { var x = 20 (function() { f() //10,而不是20 })() } show(fn)
在 fn 函数中,取自由变量 x 的值时,要到哪个作用域中取?——要到创建 fn 函数的那个作用域中取,无论 fn 函数将在哪里调用。
所以,不要在用以上说法了。相比而言,用这句话描述会更加贴切:要到创建这个函数的那个域”。
作用域中取值,这里强调的是“创建”,而不是“调用”,切记切记——其实这就是所谓的"静态作用域"
var a = 10 function fn() { var b = 20 function bar() { console.log(a + b) //30 } return bar } var x = fn(), b = 200 x() //bar()
fn()返回的是 bar 函数,赋值给 x。执行 x(),即执行 bar 函数代码。取 b 的值时,直接在 fn 作用域取出。取 a 的值时,试图在 fn 作用域取,但是取不到,只能转向创建 fn 的那个作用域中去查找,结果找到了,所以最后的结果是 30
许多开发人员经常混淆作用域和执行上下文的概念,误认为它们是相同的概念,但事实并非如此。
我们知道 JavaScript 属于解释型语言,JavaScript 的执行分为:解释和执行两个阶段,这两个阶段所做的事并不一样:
JavaScript 解释阶段便会确定作用域规则,因此作用域在函数定义时就已经确定了,而不是在函数调用时确定,但是执行上下文是函数执行之前创建的。执行上下文最明显的就是 this 的指向是执行时确定的。而作用域访问的变量是编写代码的结构确定的。
作用域和执行上下文之间最大的区别是:
执行上下文在运行时确定,随时可能改变;作用域在定义时就确定,并且不会改变。
一个作用域下可能包含若干个上下文环境。有可能从来没有过上下文环境(函数从来就没有被调用过);有可能有过,现在函数被调用完毕后,上下文环境被销毁了;有可能同时存在一个或多个(闭包)。同一个作用域下,不同的调用会产生不同的执行上下文环境,继而产生不同的变量的值。
相关免费学习推荐:js视频教程
更多编程相关知识,请访问:编程入门!!
The above is the detailed content of Detailed explanation of scope and scope chain in JavaScript. For more information, please follow other related articles on the PHP Chinese website!