当前位置:网站首页>Scope of ES6 variable
Scope of ES6 variable
2022-06-25 13:20:00 【acgCode】
JavaScript Update to ES6, Added a new let and const Two commands to declare variables . I combine var The scopes of these three commands are compared .
| Command name | Scope |
|---|---|
| var | overall situation |
| let | Block level |
| const | Block level |
In order to see the difference more directly , You can see the following code :
for (var var_i = 0; var_i < 3; var_i++) {
{
console.log(var_i);
}
}
// Global scope
console.log(var_i);
for (let let_i = 0; let_i < 3; let_i++) {
{
console.log(let_i);
}
}
// Block level scope
// console.log(let_i);
{
const CONST_I = "const";
console.log(CONST_I);
}
// Block level scope
// console.log(CONST_I);
The output is :
var: 0
var: 1
var: 2
var: 3
let: 0
let: 1
let: 2
const: const
You can see the source code for let and const Output out of block , I just commented it out . because let and const It's a block level scope , Output outside the block will directly report an error .
This feature can explain many problems , Like the ones that we see all the time for Loop binding events .
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>let Scope and var Scope differences </title>
</head>
<body>
<style> .item {
width: 100px; height: 50px; margin: 20px; border: 1px solid #3b3b3b; } </style>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</body>
</html>
use let Traverse :
let items = document.getElementsByClassName('item');
for (let index = 0; index < items.length; index++) {
items[index].onclick = function () {
items[index].style.background = 'green';
console.log(`let: ${
index}`);
}
}
Click event Normal execution , And the output is as follows :
use var Traverse :
let items = document.getElementsByClassName('item');
for (var index = 0; index < items.length; index++) {
items[index].onclick = function () {
console.log(`let: ${
index}`);
items[index].style.background = 'green';
}
}
Click event unexecuted , And the output is as follows :
It can be seen from the above that ,var Because it is a global scope , So after the loop is completed, it becomes 3, So when the click event is executed , Find the top level of the variable index Located globally , Has become 3, Array overflow , Click event cannot be executed normally ; and let Because it is a block level scope , When the click event is executed , Find the highest level of the variable in the loop body , It is still corresponding index, Click the event to execute normally .
Flexible application of variable scope , Different development effects can be achieved . Under the rigorous development mode , It is recommended to use more let and const Such block level scopes , This makes the code more secure .
边栏推荐
- API in Nova
- 汇编标志位相关知识点(连)
- Which Chinese virtual human is better? Sullivan, IDC: Xiaobing Baidu Shangtang ranks in the first echelon
- . NET in China - What's New in . NET
- OpenStack学习笔记-Glance组件深入了解
- À propos du stockage des données en mémoire
- 字符串各操作函数与内存函数详解
- OpenStack-----Nova源码分析之创建虚拟机
- Include what you use to save chaotic header files
- golang键盘输入语句scanln scanf代码示例
猜你喜欢

New Gospel of drug design: Tencent, together with China University of science and technology and Zhejiang University, developed an adaptive graph learning method to predict molecular interactions and

剑指Offer 第 2 天链表(简单)

About data storage in memory

关于结构体,枚举,联合的一些知识

Introduction to mongodb chapter 01 introduction to mongodb

An article clearly explains MySQL's clustering / Federation / coverage index, back to table, and index push down

Sword finger offer day 3 string (simple)

Summer Ending

Sword finger offer day 1 stack and queue (simple)

Seven competencies required by architects
随机推荐
Uncover gaussdb (for redis): comprehensive comparison of CODIS
数据在内存中的存储相关内容
JVM参数解释
Cold migration and resize of Nova component source code analysis
解析数仓lazyagg查询重写优化
Drago Education - typescript learning
1024 hydrology
Include what you use to save chaotic header files
Qt鼠标跟踪
关于数据在内存中存储的相关例题
Sword finger offer II 028 Flatten multi-level bidirectional linked list
Some knowledge about structure, enumeration and union
MySQL 学习笔记
J2EE from entry to earth 01 MySQL installation
Configuring pytorch in win10 environment
About data storage in memory
Django framework - caching, signaling, cross site request forgery, cross domain issues, cookie session token
初始c语言时的一些知识
JVM parameter interpretation
15 basic SEO skills to improve ranking