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!