


Introduction to the new variable declaration method in ES6 (with code)
This article brings you an introduction to the new variable declaration method in ES6 (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
In ES5, there are only three types of variable declarations: var, function, and implicit declaration. In ES6, four types are added: let, const, import, and class.
1. let
1.1 Block-level scope
The scope of the variable declared by let is the block-level scope (this feature is somewhat similar to Backend language), ES5 does not have block-level scope, only function scope and global scope.
{ let a = 'ES6'; var b = 'ES5'; } console.log(b) // ES5 console.log(a) // ReferenceError: a is not defined.
So what are the benefits of let’s block-level scope?
let is very suitable for block-level scope inside a for loop. The for loop body in JS is special. Each execution is a new independent block scope. After the variables declared with let are passed into the scope of the for loop body, they will not change and will not be affected by the outside world. Look at a common interview question:
for (var i = 0; i <10; i++) { setTimeout(function() { // 同步注册回调函数到异步的宏任务队列。 console.log(i); // 执行此代码时,同步代码for循环已经执行完成 }, 0); } // 输出结果 10 (共10个) // 这里变量为i的for循环中,i是一个全局变量,在全局范围内都有效,所以每一次循环,新的i值都会覆盖旧值,导致最后输出的是最后一轮i的值,即i的最终结果为10,实际上都是console.log(10)。涉及的知识点:JS的事件循环机制,setTimeout的机制等
Change var to let statement:
for (let i = 0; i < 10; i++) { setTimeout(function() { console.log(i); //当前的i仅在本轮的循环中有效,就是说每一次循环,i其实都是一个新产生的变量。 //用 let 声明的变量 i 只作用于循环体内部,不受外界干扰。 }, 0); } // 输出结果: 0 1 2 3 4 5 6 7 8 9
1.2 Temporary Dead Zone
In a block-level scope , variables only exist. Once a variable is declared with let in a block-level scope, the variable uniquely belongs to this block-level scope and is not affected by external variables, as shown below.
var tmp = 'bread and dream'; if(true){ tmp = 'dream or bread'; //ReferenceError let tmp; }
In this example, the assignment of tmp = 'dream or bread' will report an error because let in the if block declares the tmp variable, causing the tmp to be bound to this scope and let to temporarily die. As a result, it cannot be used before declaration, so assigning a value to a variable before declaration will cause an error.
The essence of the temporary dead zone is that as soon as the current scope is entered, the variable to be used already exists, but cannot be obtained. Only when the line of code that declares the variable appears can the variable be obtained and used. variable.
The significance of the temporary dead zone is also to allow us to standardize the code and place the declaration of all variables at the beginning of the scope.
1.3 Repeated declarations are not allowed
(1) In the same scope, when using let to declare a variable, it is only allowed to be declared once, but var can be declared multiple times. Everyone knows that multiple declarations in ES5 will cause variable coverage and no error will be reported, which makes debugging more difficult, but let can directly kill this problem in the cradle because it will directly report an error.
// 不报错 function demo() { var a = 'bread and dream'; var a = 'dream or bread'; } // 报错,Duplicate declaration "a" function demo() { let a = 'bread and dream'; var a = 'dream or bread'; } // 报错,Duplicate declaration "a" function demo() { let a = 'bread and dream'; let a = 'dream or bread'; }
(2) Parameters cannot be redeclared inside a function:
function demo1(arg) { let arg; // 报错 } demo1() function demo2(arg) { { let arg; // 不报错 } } demo2()
2. const
2.1 is used to declare constants
## Constants declared with #const are not allowed to be changed and are read-only attributes. This means that constants must be assigned a value when they are declared. If they are declared without assignment, an error will be reported. Usually constants are named with capital letters.const Person; // 错误,必须初始化 const Person = 'bread and dream';// 正确 const Person2 = 'no'; Person2 = 'dream or bread'; //报错,不能重新赋值
if (true) { const MIN = 5; } MIN // Uncaught ReferenceError: MIN is not defined
if (true) { console.log(MIN); // ReferenceError const MIN = 5; }
const obj = {}; obj.a = 'xiao hua'; console.log(obj.a); //'xiao hua'
3. import
ES6 uses import instead of require such as node to import modules.import {$} from './jquery.js'
import { JQ as $ } from './jquery.js';
4. class
ES6 introduces the concept of class and the keyword class. The essence of a class is still a function object. First define a class://定义类 class Animal { constructor(name, age) { this.name = name; this.age = age; } setSex(_sex) { this.sex=_sex; } }
function Animal(name, age){ this.name = name; this.age = age; } Animal.prototype.setSex = function (_sex) { this.sex=_sex; }
生成类的实例对象的写法,与ES5通过构造函数生成对象完全一样,也是使用new命令。
class Animal {} let dog = new Animal();
在类的实例上面调用方法,其实就是调用原型上的方法,因为类上的方法其实都是添加在原型上。
Class其实就是一个function,但是有一点不同,Class不存在变量提升,也就是说Class声明定义必须在使用之前。
5.总结
在ES6之前,JavaScript是没有块级作用域的,如果在块内使用var声明一个变量,它在代码块外面仍旧是可见的。ES6规范给开发者带来了块级作用域,let和const都添加了块级作用域,使得JS更严谨和规范。
let 与 const 相同点:
块级作用域
有暂时性死区
约束了变量提升
禁止重复声明变量
let 与 const不同点:
const声明的变量不能重新赋值,也是由于这个规则,const变量声明时必须初始化,不能留到以后赋值。
合理的使用ES6新的声明方式,不管是面试还是工作中都有实际的应用,尤其是工作中,大家一定要尽量的多使用新的声明方式,不但可以让代码更规范,更可以避免不必要的bug,浪费调试时间,进而提高工作效率。
本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注PHP中文网的JavaScript视频教程栏目!
The above is the detailed content of Introduction to the new variable declaration method in ES6 (with code). 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

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

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

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).
