Home  >  Article  >  Web Front-end  >  Introduction to the new variable declaration method in ES6 (with code)

Introduction to the new variable declaration method in ES6 (with code)

不言
不言forward
2019-03-26 10:11:332527browse

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'; //报错,不能重新赋值
This has two benefits: First, people reading the code will immediately realize that this value should not be modified, and second, it prevents errors caused by inadvertently modifying the variable value. For example, when we use some modules of nodejs, we only use the corresponding modules (such as http module), but do not need to modify the nodejs module. At this time, we can declare it as const, which increases the readability of the code and avoids errors.

2.2 Supports block-level scope

const is similar to let and also supports block-level scope.

if (true) {
  const MIN = 5;
}

MIN // Uncaught ReferenceError: MIN is not defined
2.3 Does not support variable promotion and has a temporary dead zone

Consts declared by const are not promoted. They also have a temporary dead zone and can only be used after the declared position.

if (true) {
  console.log(MIN); // ReferenceError
  const MIN = 5;
}
2.4 Special cases

If the declared constant is an object, then the object itself is not allowed to be reassigned, but the properties of the object can be assigned.

const obj = {};
obj.a = 'xiao hua';
console.log(obj.a);    //'xiao hua'
In fact, what const can guarantee is not that the value of the variable cannot be changed, but that the data stored in the memory address pointed to by the variable cannot be changed.

For simple types of data (numeric values, strings, Boolean values), the value is stored at the memory address pointed to by the variable, so it is equivalent to a constant.

But for composite type data (mainly objects and arrays), the memory address pointed to by the variable only stores a pointer to the actual data.

As for whether the data structure it points to is variable, it is completely out of control. Therefore, you must be very careful when declaring an object as a constant.

If you want to completely freeze the object (its properties cannot be modified), you should use the Object.freeze(obj) method. The same goes for arrays.

3. import

ES6 uses import instead of require such as node to import modules.

import {$} from './jquery.js'
$The object is the object exposed by export in jquery.

If you want to rename the input variable, use the as keyword in the import command to rename the input variable.

import { JQ as $ } from './jquery.js';
Note that the import command has a promotion effect and will be promoted to the head of the entire module and executed first.

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;
  }
}
The constructor method is the constructor method, which is the main body of the function object in the ES5 era, and the this keyword represents the instance object.

The above class can also be changed to ES5 writing:

function Animal(name, age){
        this.name = name;
        this.age = age;
}

Animal.prototype.setSex = function (_sex) {
        this.sex=_sex;
}
In fact, the characteristics of most classes can be deduced through the previous function objects and prototypes.

生成类的实例对象的写法,与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!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete