ES6 learning - understand ES6 in one article
Introduction to es6
The full name of ES is EcmaScript, which is the specification of scripting language, and an implementation of EcmaScript that is often written, so the new features of ES actually refer to the new features of JavaScript.
Why learn ES6
1. The ES6 version has the most changes and is a milestone.
2. ES6 has added many new grammatical features, making programming easier and more efficient
. 3. ES6 is the trend of front-end development and must be employed
ES6-let variable declaration and declaration characteristics
Declare variables:
let attribute
- Variables cannot be declared repeatedly
- Block-level scope [global scope, function scope, eval scope]
- There is no variable promotion [: the code will collect variables and functions in advance before execution, and assign initial values null and undefined] let cannot be used before variable declaration, and var can be used before being declared.
- does not affect the scope chain
The declaration of const and its characteristics
Variable declaration [declaring constants]
Attention to the use of const
- Be sure to assign an initial value
- Unspoken rules, general constants use uppercase
- Constant value cannot be modified
- Block-level scope
5. Modifications to elements of arrays and objects are not counted as modifications to constants, and no error will be reported
Struct assignment of ES6 variables
ES6 allows extracting values from arrays and objects according to a certain pattern, and assigning values to variables
- Array Destructuring
- Object deconstruction
Why object deconstruction?
Let’s look at the code first:
attribute deconstruction is less used, and method deconstruction is used more. If you don’t use method deconstruction, you need to write "zhao.xiaopin()" every time, which is more repetitive. Then you can deconstruct the object and call There is no need to write the form of "zhao.xxx" in front of the method;
under what circumstances should the deconstruction of the method be used:
the new features are created to make it more convenient for developers. When the method is called frequently, you can think of using destructuring assignment at this time to make the code more concise.
ES6 template strings
ES6 introduces the emerging way of declaring strings
- es6 string declaration
- Feature 1: A newline character can appear directly in the content.
If there is a newline character before es6, an error will be reported [Grammar error]
No error will be reported after es6 appears. Use "``" to solve the problem of grammatical error.
- Feature 2: variable splicing
Simplified writing of es6 objects
ES6 allows variables and functions to be directly written in braces as properties and methods of objects, simplifying the steps for programmers to write code.
- Variable form simplifies object writing
- Method declaration simplifies
the cumbersome writing of object methods before es6
Simplified writing of object methods after es6
ES6 arrow function and declaration features
es6 allows the use of [arrow] (=>) to define functions
- Declare a function using a raw method and a method using an arrow function
- What is the difference between the characteristics of the arrow function declaration and the previous functions?
1. This is static. This always points to the value of this under the scope where the function is declared. The this value of the arrow function is static. No matter what method is used to call it, its this always points to the value of the function in the declaration The this value under the current scope.
Direct call:
call Method call: You can change the value of this inside the function. The following results show that call cannot change the direction of this in the arrow function.
2. Arrow functions cannot be used as constructors to instantiate objects
3. The arguments variable cannot be used [the special variable arguments inside the function is used to store actual parameters]
4. Shorthand for arrow functions,
the first of the two cases: parentheses are omitted , can be omitted when there is only one formal parameter.
The second is to omit curly braces. When the code body has only one statement, return must be omitted at this time, and the execution result of the word order is the return value of the function.
Notes on using arrow functions:
1. Arrow functions are suitable for this-independent callbacks, timers, and array method callbacks
2. Arrow functions are not suitable for thi-related callbacks, event callbacks, and object methods
Default value setting for es6 function parameters
In es6, it is allowed to assign initial values to function parameters
-
The initial value of the formal parameter
es6 In the formal parameter, one less NaN result is passed.
es6 assigns the initial value to the function. If this parameter is not passed, the default value is the initial value.
Note: the parameters with default values should generally be placed later (latent rule) -
Used in conjunction with destructuring assignment.
If passed parameters are passed, if not passed, use the default value set.
Rest parameters in es6
es6 refers to the rest parameter, which is used to obtain the actual parameters of the function, and is used to replace arguments [get all the actual parameters when the function is called]
- The way es5 gets real parameters [returned object]
- The rest parameter in es6 [returns an array]
can use "filter", some every, map to return an array, which improves the flexibility of parameter processing. - Note: If there are multiple parameters, the rest parameter must be placed at the end of the parameter.
wrong usage:
use correctly:
Introduction to es6 spread operator
The […] spread operator can convert an [array] into a comma-separated [parameter sequence].
- Example
Pass without using ..., pass an array
Pass with ...
Application of spread operator
- Merge of arrays
- array clone
- Convert pseudo array to real array
Introduction and creation of es6-Symbol
- The introduction of symbol
ES6 introduces a new primitive data type symbol, a unique value, which is the seventh data type of the javascript language and is an array type similar to strings. - The characteristics of symbol
1. The value of symbol is unique and used to resolve naming conflicts.
Second, the value of symbol cannot be operated with other data.
3. The object properties defined by symbol cannot be traversed using the for...in loop, but you can use Reflect.ownKeys to get all the key names of the object
The first way to create a symbol :
The second way to create: the symbol inside the brackets is just the sign of the symbol.
The third way: 【Symbol.for()】, symbol.for is a global symbol table, if there is one, access the corresponding object, if not, create it.
es6-objects add attributes of symbol type
Using symbols to add objects and properties, we can quickly and safely add objects to the game without destroying the original properties and methods.
- The first method of adding
- The second addition
ES6-Symbol built-in values
In addition to defining the Symbol value used by itself, ES6 also provides many built-in Symbol values, pointing to the methods used internally by the language.
- Symbol.hasInstance
- isConcatSpreadable
es6-iterator
An iterator is an interface that provides a unified access mechanism for various data structures. Any data deconstruction can complete the traversal operation as long as the iterator interface is deployed.
- ES6 has created a new traversal command for ... of loop, the iterator interface is mainly for consumption by for ... or
- Data with native iterator interface can be traversed by for of, Array, Arguments, Set, map, string, typeArray, NodeList
- working principle
a. 创建一个指针,指向当前数据结构的起始位置。 b. 第一次调用对象的next方法,指针自动指向数据结构的第一个成员, c. 接下来不断调用next方法,指针一直往后移动,知道只想最后一个成员。 d. 每调用next方法返回一个包含value和done属性的对象 **注意:需要自定义遍历数据的时候要想到迭代器**
- for...of loop [output key value]
- for...in loop [output key name]
Iterator application - custom traversal data
Customize the iterator to traverse the data according to the working principle of the iterator
<script>
//声明一个对象
const banji = {
name:"终极一班",
stus:['小明','小天','小吴','小王',],
[Symbol.iterator](){
//索引变量
let index = 0;
//指向
let _this = this;
return {
next:function(){
if(index<_this.stus.length){
const result = {
value:_this.stus[index],done:false}
//下标自增
index++;
//返回结果
return result;
}else{
return {
value:undefined,done:true}
}
}
}
}
}
//遍历这个对象
for(let v of banji){
console.log(v);
}
</script>
Effect:
es6-generator function declaration and call
The generator function is an asynchronous programming solution provided by ES6. The grammatical behavior is completely different from the traditional function. In fact, it is a special function for asynchronous programming. The pure callback function node \fs \ ajax \ mongodb was used
before
- Declaration and calling method:
- The generator can use the yield statement
yield can be counted as a separator of the function code
The yield statement can be used as a separator, using the next call
- Using for-of to traverse generators
- The generator's principle output explains what yield does:
Parameter passing for ES6 generator functions
The next called by the generator can pass an actual parameter, and this actual parameter is the entire return result of the yield statement.
- pass parameters to the whole function
- The next method can also pass parameters, and this parameter will be used as the return result of the previous yeild statement, and the second call returns the overall return result of the first yeild statement. . .
es6 generator function instance
Asynchronous programming: file operation, network operation (ajax, request) database operation
Example: 1s output 111, 2s output 222, 3s output 333
layers of callbacks, it will become a callback
hell The above code will enter the callback hell, the following will not work
Example 2, Simulate acquisition, user data, order data, product data
call:
es6-promise learning and use
Introduction and basic use of es6-promise
Promise is a new solution for asynchronous programming introduced by ES6. Promise is a constructor that encapsulates asynchronous operations and can obtain odd success or failure results [Solve the callback hell problem]
- Promise constructor:
Promise {excutor}{ }
Promise.prototype.then
methodPromise.prototype.catch
method
1. Instantiate the Promise object.
The Promise object has three states, initialization, success, and failure.
Instantiate the promise object:
//实例化Promise对象【三个状态:初始化,成功,失败】
const p = new Promise(function(resolve,reject){
setTimeout(() => {
let data = "数据库中的用户数据"
//resolve调用
resolve(data);
}, 1000);
});
Both success and failure of the call will execute the method of promise.then. The method of then has two parameters, both of which are values of function type. Each function has a formal parameter. If the first function of then is executed successfully, it fails. The second execution parameter of the execution, the formal parameters of the two functions are value and reason, the successful one is called value, and the failed one is called reson.
Call then code:
/*
调用成功,就会调用promise对象的then方法,
then方法接受两个参数,
两个参数都是函数类型的值,每个函数都有一个形参,成功的叫做value,失败的叫做reason
调到resolve代表成功,读取状态成功,then就会执行第一个回调函数代码
如果读取状态失败,调用带有
*/
p.then(
function(value){
console.log(value);
},
function(reason){
}
)
Successful call output:
read failed example:
const p = new Promise(function(resolve,reject){
setTimeout(() => {
//
let data = "数据库中的用户数据"
let err = "读取数据库失败"
//resolve调用
reject(err)
}, 1000);
});
p.then(function(value){
console.log(value);
},function(reason){
console.log(reason);
})
es6-promise package read file
Native js output file content [request file content is asynchronous]
//引入fs模块
const fs = require('fs');
//调用方法读取文件
fs.readFile('./resources/1.md',(err,data)=>{
//如果失败则抛出错误
if(err) throw err;
//如果没有出错,则输出内容
console.log(data.toString());
})
Effect:
use promise package to read the file:
//3.使用promise封装
const p = new Promise(function(resolve,reject){
fs.readFile("./resources/1.md",(err,data)=>{
//判断读取失败
if(err) reject(err);
//如果成功
resolve(data)
})
})
p.then(
function(value){
console.log(value.toString());
},
function(reason){
console.log(reason);
})
Effect:
es6-promise encapsulates Ajax requests
- Native Ajax request data
<script>
//接口地址:https://api.apiopen.top/getJoke
//创建对象
const xhr = new XMLHttpRequest();
//初始化
xhr.open("GET","https://api.apiopen.top/getJoke");
//发送
xhr.send();
//4.绑定时间,处理响应结果
xhr.onreadystatechange = function(){
//判断
if(xhr.readyState === 4){
//判断响应状态吗 200-299
if(xhr.status >= 200 && xhr.status < 300){
//表示成功
console.log(xhr.response);
}else{
//如果失败
console.log(xhr.status);
}
}
}
</script>
Result of request success:
Result of request failure:
2. Promise encapsulates Ajax code
<script>
//接口地址:https://api.apiopen.top/getJoke
const p = new Promise((resolve,reject)=>{
//创建对象
const xhr = new XMLHttpRequest();
//初始化
xhr.open("GET","https://api.apiopen.top/getJoke");
//发送
xhr.send();
//4.绑定时间,处理响应结果
xhr.onreadystatechange = function(){
//判断
if(xhr.readyState === 4){
//判断响应状态吗 200-299
if(xhr.status >= 200 && xhr.status < 300){
//表示成功
resolve(xhr.response)
}else{
//如果失败
reject(xhr.status);
}
}
}
});
//指定回调
p.then(
function(value){
console.log(value);
},
function(reason){
console.log(reason);
})
</script>
Success effect:
Failure effect:
The processing method is different. It turns out that the results of success and failure are processed in the callback function. Promise is used to specify the callback through then after the asynchronous task. The structure is clear and there will be no problem of callback hell.
es6-Promise.prototype.then method
-
then return result: the return result is determined by the callback result of the execution function. If the result returned in the callback function is a ||promise type attribute, the status is success, and the return value is the success value of the object.
-
then returns a non-Promise object
//创建promise对象
const p = new Promise((resolve,reject)=>{
setTimeout(()=>{
//resolve("请求成功")
reject("请求失败")
},1000)
});
//调用 then方法
const result = p.then(value =>{
console.log(value);
return value;
},reason =>{
console.log(reason);
return reason;
})
console.log(result);
Do not write return
the return undefined
result:
3. then returns the Promise object
then returns the Promise object, the state of the promise in then determines the state of an object returned by the then method, and the failure of the Promise in then determines the state of a failure returned by the then method.
//创建promise对象
const p = new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve("请求成功")
//reject("请求失败")
},1000)
});
//调用 then方法
const result = p.then(value =>{
return new Promise((resolve,reject)=>{
resolve('ok')
})
},reason =>{
console.log(reason);
})
console.log(result);
4. then throws an error
[if an error is thrown, this state is also a failed Promise state, and the value of the error is the value thrown]
//创建promise对象
const p = new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve("请求成功")
//reject("请求失败")
},1000)
});
//调用 then方法
const result = p.then(value =>{
//抛出错误
throw new Error("出错啦")
},reason =>{
console.log(reason);
})
console.log(result);
Effect:
Since the then method can return a promise object, the then method can be called in a chain, and the chain call [when the then method specifies a callback, only one can be specified, and the problem of callback hell can be changed through a chain call]
format :
p.then(value=>{
//异步任务
},reason=>{
//异步任务
}).then(value=>{
//异步任务
},reason=>{
//异步任务
})
es6-promise practical exercise - multiple file content reading
//回调地狱容易重名,很不容易被发现
- Do it the callback hell way
//引入fs模块
const fs = require("fs")
fs.readFile('./resources/1.md',(err,data)=>{
fs.readFile('./resources/2.md',(err,data1)=>{
fs.readFile('./resources/3.md',(err,data2)=>{
let result = data+"\r\n"+data1+"\r\n"+data2
console.log(result);
});
});
});
It can be found from the above code that the callback hell is easy to have the same name, and it is not easy to be found.
Promise implementation:
//使用promise来实现
const p = new Promise((resolve,reject)=>{
fs.readFile("./resources/1.md",(err,data)=>{
resolve(data);
})
})
p.then(value=>{
return new Promise((resolve,reject)=>{
fs.readFile("./resources/2.md",(err,data)=>{
resolve([value,data]);
});
});
}).then(value=>{
return new Promise((resolve,reject)=>{
fs.readFile("./resources/3.md",(err,data)=>{
//压入
value.push(data);
resolve(value)
});
});
}).then(value=>{
console.log(value.join('\r\n'));
})
es6-Promise object catch method
catch is used to specify a callback for promise failure
The first method code:
<script>
const p = new Promise((resolve,reject)=>{
setTimeout(()=>{
//设置p对象的状态为失败,并且设置失败的值
reject("出错啦")
})
})
p.then(function(value){
},function(reason){
console.error(reason);
})
</script>
Effect:
Second way code:
<script>
const p = new Promise((resolve,reject)=>{
setTimeout(()=>{
//设置p对象的状态为失败,并且设置失败的值
reject("出错啦")
})
})
p.catch(function(reason){
console.warn(reason);
})
</script>
es6-collection introduction and API
set introduction
ES6 provides a new data structure Set (collection). It is similar to an array, but the values of the members are all unique collections that implement the iterator interface, so you can use [extension operator] and [for…of…] to traverse
The properties and methods of the collection:
1) size: return the number of elements in the collection
2) add: add a new element and return the current collection
3) delete: delete the element and return a boolean value
4) has: check whether the collection contains a certain element, returns a boolean value
Simply understand Set through code:
//声明一个set
let s = new Set();
//可以写入可迭代数据,可以去重
let s2 = new Set(['大事儿','小事儿','坏事儿','小事儿','很多事儿','大事儿'])
console.log(s,typeof s);
console.log(s2);
Effects:
Introductory code and effects for collection properties and methods
//元素个数
let s2 = new Set(['大事儿','小事儿','坏事儿','小事儿','很多事儿','大事儿'])
console.log(s2.size);
//向集合里添加新的元素
s2.add("喜事儿")
console.log("集合添加后有:"+s2.size+"个",s2);
//删除元素
s2.delete("坏事儿")
console.log("集合删除后有:"+s2.size+"个",s2);
//检测【检测集合中有没有该元素】
console.log(s2.has('喜事儿'));
//可以使用for...of...遍历
for(let v of s2){
console.log(v);
}
//清空集合
s2.clear();
console.log(s2);
Effect:
es6-collection practice
Two arrays are already known:
let arr = [1,2,3,4,5,4,3,2,1,5,4,5,8,9,54,4,1]
let arr2 = [54,1,3,4,6,9,8]
- Array deduplication
//1.数组去重
let result = [...new Set(arr)]
console.log(result);
2. Intersection of two arrays
//2.交集
let arr2 = [54,1,3,4,6,9,8]
let result2 = [...new Set(arr)].filter(item=>{
let s2 = new Set(arr2)
if(s2.has(item)){
return true
}else{
return false
}
})
console.log(result2);
//简化版求交集
let result3 =[...new Set(arr)].filter(item=>new Set(arr2).has(item))
console.log(result3);
3. The union of two arrays
//3.并集
let result4 =[...new Set([...arr,...arr2])]
console.log(result4);
Effect:
4. Find the difference of two arrays [inverse operation of intersection]
//4.差集
let result5 = [...new Set(arr)].filter(item=>{
let s2 = new Set(arr2)
if(!s2.has(item)){
return true
}else{
return false
}
})
let result6 =[...new Set(arr)].filter(item=>!new Set(arr2).has(item))
console.log(result5);
console.log(result6);
Effect:
Introduction and API of es6-Map
ES6 provides a map data structure, which is similar to an object and a collection of key-value pairs, but the scope of "key" is not limited to strings, and various types of values (including objects) can be used as keys, and map also implements the iterator interface , so you can use [extension operator] and [for...of...] to traverse, map attributes and methods:
- size Returns the number of elements in the map
- size is a new element, returns the current map
- get returns the key value of the key object
- has detects whether an element is contained in the map and returns a bollean value
- clear clears the collection, returns undefined,
declares a Map and adds
//声明 Map
let m = new Map();
//添加元素
m.set('name','吴又可');
m.set('change',function(){
console.log("无用的方法");
});
console.log(m);
map adds a second method
//声明 Map
let m = new Map();
//添加元素
m.set('name','吴又可');
m.set('change',function(){
console.log("无用的方法");
});
let key = {
school : "sgg"
};
m.set(key,['北京','上海','广州']);
console.log(m);
Effect:
Other APIs of map
//添加
m.set(key,['北京','上海','广州']);
//删除
m.delete('name')
console.log(m);
//获取
console.log(m.get('change'));
console.log(m.get(key));
//遍历
for(let v of m){
console.log(v);
}
//清空
m.clear();
es6-class class
ES6 provides a writing method that is closer to the traditional language, and introduces the concept of the Class class. As an object template, the class can be defined through the class keyword. Basically, the class of ES6 can be regarded as just a syntactic sugar. Most of it Function, es5 can do it, the new class writing method just makes the circular writing method of the object clearer, more like the syntax of object-oriented programming.
-
Knowledge points:
(1) class declares class
(2) constructor defines constructor initialization
(3) extends inherits parent class
(4) static defines static methods and properties
(5) super calls parent constructor
(6) parent class method can be repeated Write -
Review the use of Es6 classes
// 手机
function Phone(brand,price){
this.brand = brand;
this.price = price;
}
//添加方法
Phone.prototype.call = function(){
console.log("我可以打电话");
}
//实例化对象
let Huawei = new Phone('华为',5999);
Huawei.call();
console.log(Huawei);
Use effect:
3. The use of es6 class
// class
class Phone{
//构造方法,名字不能修改,当实例化的时候会自动执行
constructor(brand,price){
this.brand = brand;
this.price = price;
}
//方法必须使用该语法,不能使用es5的对象完整形式
call(){
console.log("我可以打电话");
}
}
let onePlus = new Phone("huawei",4999);
console.log(onePlus);
The effect of class usage in es6
Static members in Class in es6
static members in es5
In es5, the properties of the instance object and the function object are not the same. The properties of the instance object are the same as the prototype object of the constructor. The implicit prototype of the instance object points to the prototype object of the constructor
function Phone(){
}
Phone.name = "手机";
Phone.change = function(){
console.log("我可以改变世界");
}
Phone.prototype.size = "5.5inch"
let nokia = new Phone();
console.log(nokia.name);
console.log(nokia.size);
npkia.change();
Effect: