


JavaScript ES6 adds a new introduction to the use of let command (picture and text tutorial)
ES6 adds a new let command to declare variables. Its usage is similar to var, but the declared variable is only valid within the code block where the let command is located
let
Command
Basic usage
ES6 adds a new let command to declare variables. Its usage is similar to var, but the declared variable is only valid within the code block where the let command is located.
{ let a = 10; var b = 1; } a // ReferenceError: a is not defined. b // 1
The above code is in the code block and declares two variables using let and var respectively. Then these two variables are called outside the code block. As a result, the variable declared by let reports an error, and the variable declared by var returns the correct value. This shows that the variable declared by let is only valid in the code block in which it is located.
For loop counter, it is very suitable to use the let command.
for (let i = 0; i < 10; i++) {} console.log(i); //ReferenceError: i is not defined
In the above code, counter i is only valid within the body of the for loop, and an error will be reported if it is referenced outside the loop.
If the following code uses var, the final output is 10.
var a = []; for (var i = 0; i < 10; i++) { a[i] = function () { console.log(i); }; } a[6](); // 10
In the above code, the variable i is declared by var and is valid in the global scope. So every time it loops, the new i value will overwrite the old value, causing the final output to be the value of i in the last round.
If let is used, the declared variables are only valid within the block-level scope, and the final output is 6.
var a = []; for (let i = 0; i < 10; i++) { a[i] = function () { console.log(i); }; } a[6](); // 6
In the above code, the variable i is declared by let. The current i is only valid in this cycle, so i in each cycle is actually a new variable, so the final output is 6.
No variable promotion
let does not have the "variable promotion" phenomenon like var. Therefore, variables must be used after they are declared, otherwise an error will be reported.
console.log(foo); // 输出undefined console.log(bar); // 报错ReferenceError var foo = 2; let bar = 2;
In the above code, the variable foo is declared with the var command, and variable promotion will occur. That is, when the script starts running, the variable foo already exists, but has no value, so undefined will be output. The variable bar is declared with the let command, and no variable promotion will occur. This means that the variable bar does not exist before declaring it, and if it is used, an error will be thrown.
Temporary dead zone
As long as the let command exists in the block-level scope, the variables it declares will be "binding" in this area and will no longer be affected by the let command. external influences.
var tmp = 123; if (true) { tmp = 'abc'; // ReferenceError let tmp; }
In the above code, there is a global variable tmp, but let declares a local variable tmp in the block-level scope, causing the latter to bind this block-level scope, so before let declares the variable, tmp Assignment will report an error.
ES6 clearly stipulates that if there are let and const commands in a block, the variables declared by these commands in this block will form a closed scope from the beginning. Any use of these variables before declaration will result in an error.
In short, within the code block, the variable is not available until it is declared using the let command. Grammatically, this is called a "temporary dead zone" (TDZ).
if (true) { // TDZ开始 tmp = 'abc'; // ReferenceError console.log(tmp); // ReferenceError let tmp; // TDZ结束 console.log(tmp); // undefined tmp = 123; console.log(tmp); // 123 }
In the above code, before the let command declares the variable tmp, it belongs to the "dead zone" of the variable tmp.
The "temporary dead zone" also means that typeof is no longer a 100% safe operation.
typeof x; // ReferenceError let x;
In the above code, the variable x is declared using the let command, so before it is declared, it belongs to the "dead zone" of x. As long as the variable is used, an error will be reported. Therefore, typeof will throw a ReferenceError when running.
For comparison, if a variable is not declared at all, using typeof will not report an error.
typeof undeclared_variable // "undefined"
In the above code, undeclared_variable is a variable name that does not exist, and the result is "undefined". Therefore, before let, the typeof operator was 100% safe and would never report an error. This is no longer true. This design is to help everyone develop good programming habits. Variables must be used after they are declared, otherwise an error will be reported.
Some "dead zones" are hidden and not easy to find.
function bar(x = y, y = 2) { return [x, y]; } bar(); // 报错
In the above code, the reason why an error is reported when calling the bar function (some implementations may not report an error) is because the default value of parameter x is equal to another parameter y, and y has not been declared at this time, which belongs to the "dead zone" ". If the default value of y is x, no error will be reported because x has been declared at this time.
function bar(x = 2, y = x) { return [x, y]; } bar(); // [2, 2]
ES6 stipulates that variable promotion does not occur in temporary dead zones and let and const statements, mainly to reduce runtime errors and prevent the variable from being used before the variable is declared, resulting in unexpected behavior. Such errors are very common in ES5, and now with this provision, it is easy to avoid such errors.
In short, the essence of the temporary dead zone is that as soon as you enter the current scope, the variable you want to use already exists, but it cannot be obtained. You can only obtain and obtain it until the line of code that declares the variable appears. Use this variable.
Does not allow repeated declarations
let does not allow repeated declarations of the same variable in the same scope.
// 报错 function () { let a = 10; var a = 1; } // 报错 function () { let a = 10; let a = 1; }
Therefore, parameters cannot be redeclared inside a function.
function func(arg) { let arg; // 报错 } function func(arg) { { let arg; // 不报错 } }
Block-level scope
Why do we need block-level scope?
ES5 only has global scope and function scope, but no block-level scope, which brings many unreasonable scenarios.
In the first scenario, the inner variable may overwrite the outer variable.
var tmp = new Date(); function f() { console.log(tmp); if (false) { var tmp = "hello world"; } } f(); // undefined
In the above code, after function f is executed, the output result is undefined. The reason is that the variable is promoted, causing the inner tmp variable to overwrite the outer tmp variable.
第二种场景,用来计数的循环变量泄露为全局变量。
var s = 'hello'; for (var i = 0; i < s.length; i++) { console.log(s[i]); } console.log(i); // 5
上面代码中,变量i只用来控制循环,但是循环结束后,它并没有消失,泄露成了全局变量。
ES6的块级作用域
let实际上为JavaScript新增了块级作用域。
function f1() { let n = 5; if (true) { let n = 10; } console.log(n); // 5 }
上面的函数有两个代码块,都声明了变量n,运行后输出5。这表示外层代码块不受内层代码块的影响。如果使用var定义变量n,最后输出的值就是10。
ES6允许块级作用域的任意嵌套。
{{{{{let insane = 'Hello World'}}}}};
上面代码使用了一个五层的块级作用域。外层作用域无法读取内层作用域的变量。
{{{{ {let insane = 'Hello World'} console.log(insane); // 报错 }}}};
内层作用域可以定义外层作用域的同名变量。
{{{{ let insane = 'Hello World'; {let insane = 'Hello World'} }}}};
块级作用域的出现,实际上使得获得广泛应用的立即执行函数表达式(IIFE)不再必要了。
// IIFE 写法 (function () { var tmp = ...; ... }()); // 块级作用域写法 { let tmp = ...; ... }
块级作用域与函数声明
函数能不能在块级作用域之中声明,是一个相当令人混淆的问题。
ES5规定,函数只能在顶层作用域和函数作用域之中声明,不能在块级作用域声明。
// 情况一 if (true) { function f() {} } // 情况二 try { function f() {} } catch(e) { }
上面代码的两种函数声明,根据ES5的规定都是非法的。
但是,浏览器没有遵守这个规定,为了兼容以前的旧代码,还是支持在块级作用域之中声明函数,因此上面两种情况实际都能运行,不会报错。不过,“严格模式”下还是会报错。
// ES5严格模式 'use strict'; if (true) { function f() {} } // 报错
ES6 引入了块级作用域,明确允许在块级作用域之中声明函数。
// ES6严格模式 'use strict'; if (true) { function f() {} } // 不报错
ES6 规定,块级作用域之中,函数声明语句的行为类似于let,在块级作用域之外不可引用。
function f() { console.log('I am outside!'); } (function () { if (false) { // 重复声明一次函数f function f() { console.log('I am inside!'); } } f(); }());
上面代码在 ES5 中运行,会得到“I am inside!”,因为在if内声明的函数f会被提升到函数头部,实际运行的代码如下。
// ES5版本 function f() { console.log('I am outside!'); } (function () { function f() { console.log('I am inside!'); } if (false) { } f(); }());
ES6 的运行结果就完全不一样了,会得到“I am outside!”。因为块级作用域内声明的函数类似于let,对作用域之外没有影响,实际运行的代码如下。
// ES6版本 function f() { console.log('I am outside!'); } (function () { f(); }());
很显然,这种行为差异会对老代码产生很大影响。为了减轻因此产生的不兼容问题,ES6在附录B里面规定,浏览器的实现可以不遵守上面的规定,有自己的行为方式。
允许在块级作用域内声明函数。
函数声明类似于var,即会提升到全局作用域或函数作用域的头部。
同时,函数声明还会提升到所在的块级作用域的头部。
注意,上面三条规则只对ES6的浏览器实现有效,其他环境的实现不用遵守,还是将块级作用域的函数声明当作let处理。
前面那段代码,在 Chrome 环境下运行会报错。
// ES6的浏览器环境 function f() { console.log('I am outside!'); } (function () { if (false) { // 重复声明一次函数f function f() { console.log('I am inside!'); } } f(); }()); // Uncaught TypeError: f is not a function
上面的代码报错,是因为实际运行的是下面的代码。
// ES6的浏览器环境 function f() { console.log('I am outside!'); } (function () { var f = undefined; if (false) { function f() { console.log('I am inside!'); } } f(); }()); // Uncaught TypeError: f is not a function
考虑到环境导致的行为差异太大,应该避免在块级作用域内声明函数。如果确实需要,也应该写成函数表达式,而不是函数声明语句。
// 函数声明语句 { let a = 'secret'; function f() { return a; } } // 函数表达式 { let a = 'secret'; let f = function () { return a; }; }
另外,还有一个需要注意的地方。ES6的块级作用域允许声明函数的规则,只在使用大括号的情况下成立,如果没有使用大括号,就会报错。
// 不报错 'use strict'; if (true) { function f() {} } // 报错 'use strict'; if (true) function f() {}
do 表达式
本质上,块级作用域是一个语句,将多个操作封装在一起,没有返回值。
{ let t = f(); t = t * t + 1; }
上面代码中,块级作用域将两个语句封装在一起。但是,在块级作用域以外,没有办法得到t的值,因为块级作用域不返回值,除非t是全局变量。
现在有一个提案,使得块级作用域可以变为表达式,也就是说可以返回值,办法就是在块级作用域之前加上do,使它变为do表达式。
let x = do { let t = f(); t * t + 1; };
上面代码中,变量x会得到整个块级作用域的返回值。
JavaScript ES6 的 let 和 var 的比较
在javascript 1.7中, let 关键词被添加进来, 我听说它声明之后类似于”本地变量“, 但是我仍然不确定它和 关键词 var 的具体区别。
回答:
不同点在于作用域, var关键词的作用域是最近的函数作用域(如果在函数体的外部就是全局作用域), let 关键词的作用域是最接近的块作用域(如果在任何块意外就是全局作用域),这将会比函数作用域更小。
同样, 像var 一样, 使用let 声明的变量也会在其被声明的地方之前可见。
下面是Demo 例子。
全局(Global)
当在函数体之外它们是平等的。
let me = 'go'; //globally scoped var i = 'able'; //globally scoped
函数(Function)
当瞎下面这种, 也是平等的。
function ingWithinEstablishedParameters() { let terOfRecommendation = 'awesome worker!'; //function block scoped var sityCheerleading = 'go!'; //function block scoped };
块(Block)
这是不同点, let 只是在 for 循环中, var 却是在整个函数都是可见的。
function allyIlliterate() { //tuce is *not* visible out here for( let tuce = 0; tuce < 5; tuce++ ) { //tuce is only visible in here (and in the for() parentheses) }; //tuce is *not* visible out here }; function byE40() { //nish *is* visible out here for( var nish = 0; nish < 5; nish++ ) { //nish is visible to the whole function }; //nish *is* visible out here };
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
ES6Detailed explanation of the steps to implement full-screen scrolling plug-in
Detailed explanation of the use of Class features in es6
The above is the detailed content of JavaScript ES6 adds a new introduction to the use of let command (picture and text tutorial). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Users may have seen the term wapi when using the Internet, but for some people they definitely don’t know what wapi is. The following is a detailed introduction to help those who don’t know to understand. What is wapi: Answer: wapi is the infrastructure for wireless LAN authentication and confidentiality. This is like functions such as infrared and Bluetooth, which are generally covered near places such as office buildings. Basically they are owned by a small department, so the scope of this function is only a few kilometers. Related introduction to wapi: 1. Wapi is a transmission protocol in wireless LAN. 2. This technology can avoid the problems of narrow-band communication and enable better communication. 3. Only one code is needed to transmit the signal

Pubg, also known as PlayerUnknown's Battlegrounds, is a very classic shooting battle royale game that has attracted a lot of players since its popularity in 2016. After the recent launch of win11 system, many players want to play it on win11. Let's follow the editor to see if win11 can play pubg. Can win11 play pubg? Answer: Win11 can play pubg. 1. At the beginning of win11, because win11 needed to enable tpm, many players were banned from pubg. 2. However, based on player feedback, Blue Hole has solved this problem, and now you can play pubg normally in win11. 3. If you meet a pub

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

i5 is a series of processors owned by Intel. It has various versions of the 11th generation i5, and each generation has different performance. Therefore, whether the i5 processor can install win11 depends on which generation of the processor it is. Let’s follow the editor to learn about it separately. Can i5 processor be installed with win11: Answer: i5 processor can be installed with win11. 1. The eighth-generation and subsequent i51, eighth-generation and subsequent i5 processors can meet Microsoft’s minimum configuration requirements. 2. Therefore, we only need to enter the Microsoft website and download a "Win11 Installation Assistant" 3. After the download is completed, run the installation assistant and follow the prompts to install Win11. 2. i51 before the eighth generation and after the eighth generation

After updating to the latest win11, many users find that the sound of their system has changed slightly, but they don’t know how to adjust it. So today, this site brings you an introduction to the latest win11 sound adjustment method for your computer. It is not difficult to operate. And the choices are diverse, come and download and try them out. How to adjust the sound of the latest computer system Windows 11 1. First, right-click the sound icon in the lower right corner of the desktop and select "Playback Settings". 2. Then enter settings and click "Speaker" in the playback bar. 3. Then click "Properties" on the lower right. 4. Click the "Enhance" option bar in the properties. 5. At this time, if the √ in front of "Disable all sound effects" is checked, cancel it. 6. After that, you can select the sound effects below to set and click

PyCharm is a powerful Python integrated development environment with rich functions and tools that can greatly improve development efficiency. Among them, the replacement function is one of the functions frequently used in the development process, which can help developers quickly modify the code and improve the code quality. This article will introduce PyCharm's replacement function in detail, combined with specific code examples, to help novices better master and use this function. Introduction to the replacement function PyCharm's replacement function can help developers quickly replace specified text in the code

Many users have printer drivers installed on their computers but don't know how to find them. Therefore, today I bring you a detailed introduction to the location of the printer driver in the computer. For those who don’t know yet, let’s take a look at where to find the printer driver. When rewriting content without changing the original meaning, you need to The language is rewritten to Chinese, and the original sentence does not need to appear. First, it is recommended to use third-party software to search. 2. Find "Toolbox" in the upper right corner. 3. Find and click "Device Manager" below. Rewritten sentence: 3. Find and click "Device Manager" at the bottom 4. Then open "Print Queue" and find your printer device. This time it is your printer name and model. 5. Right-click the printer device and you can update or uninstall it.

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest
