Foreword ES6 Knowledge points study arrangement and record


This chapter shares ES6 grammar core commonly used knowledge point development must be – the interview must;

  • let , const
  • Deconstruction assignment
  • String, re, array, object, function extension + Symbol
  • Set, Map Data structure,
  • Proxy Proxy/intercept, Reflect
  • The Generator function
  • Async function
  • Promise object
  • Class class
  • The module module,

For ES6 knowledge points to do a brief overview and practice, commonly used core knowledge points will be told a little bit more detailed, the other are slightly over, I am also struggling in the study of small white, hope you big guys a lot of advice.

ES6 adds the let, const command to declare variables. Its use is similar to var;

Let let declare a block-level variable 1, there is no variable promoted n = 10; let n ; // Let n = 1; // Let n = 1; Var m = 2} // n is not defined, m // 2 3, {let n = 1; let n; } // The console will report an error, not to allow repeated declarations

Const const declares a read-only constant. Once declared, the value of the constant cannot be changed; 1, const n = 10 cannot be modified after a constant declaration; n = 101; // If you declare an array or an object, you can write values, but you can’t assign values directly

const arr = [];
arr.push(1) / / [1]
arr[1] = 2 / / [1, 2]
arr = [1.2.3] // The console will report an error telling you that constants cannot be assigned
Copy the code

Deconstruction assignment

ES6 allows fetching values from arrays and objects and assigning values to variables in a pattern known as Destructuring.

To put it crudely: unstructure variables to assign values to corresponding structures, hahaha, with a simple example

var a = 1;
var b = 2;
var c = 3;
// ES5 simplifies a bit
var a = 1, b = 2, c = 3;
// ES6 is written like this
var [a, b, c] = [1.2.3];
Copy the code

Isn’t that easy? That’s pattern matching, so as long as the structure patterns on both sides are the same, the variables on the left will be assigned to the values on the right. Let’s look at a few more cases

Destruct assignment of arrays

let [a, [[b], c]] = [1The [[2].3]];
a / / 1
b / / 2
c / / 3

let [ , , c] = ["a"."b"."c"];
c // "c"

let [x, , y] = [1.2.3];
x / / 1
y / / 3

let [x, ...arr] = [];
x  / / 1
arr // [2, 3, 4]... The expansion operator that we'll talk about later

let [x, y, ...z] = ['a'];
x // "a"
y // undefined
z / / []
Copy the code


var { a, b} = { a: "aaa".b: "bbb" };
a // aaa
b // bbb

var { b, a } = { a: "aaa".b: "bbb" };
a // "aaa"
b // "bbb"

var { c } = { a: "aaa".b: "bbb" };
c // undefined

/ / see an extension, the above var = {a, b} {a: "aaa", b: "BBB"}; It actually looks like this
var { a: a, b: b } = { a: "aaa".b: "bbb" };
a // aaa 
b // bbb 

// Let's try another way
var { a: aa, b: bb } = { a: "aaa".b: "bbb" };
a // a is not defined
b // a is not defined
// -- dividing line --
aa // aaa
bb // bbb

Key :value; key:value
Copy the code

And strings, and booleans, and the way functions can be deconstructed and assigned, and I’m not going to list them all,


  • Simplify variable declaration, fast and convenient
  • Simplify array, object manipulation
  • Function arguments are assigned by default
  • If the pattern on the left of the equals sign does not match the value on the right, undefined or XX is not defined is output by default

String, re, array, object, function extension + Symbol

When it comes to these types of expansion is more relaxed and happy, why say so, because read the official documents of small partners must be shocked, all kinds of god operation, all kinds of simplified, all kinds of cool, there is a good saying, has been working overtime a straight, here I want to say: has been extended a straight.

Extension of arrays

The array.from () array. from method converts two types of objects into true arrays: array-like objects and iterable objects (including the new ES6 data structures Set and Map).

1, here is an array-like object, array. from turns it into a real Array.

var arr = {
    '0': 'a'.'1': 'b'.'2': 'c'.length: 3
// ES5
var arr1 = []; // ['a', 'b', 'c']
// ES6
let arr2 = Array.from(arr); // ['a', 'b', 'c']
Copy the code

Let’s do another example

// Map objects will be added later in ES6
var map = new Map()
map // Map(0) {}
Array.from(map) / / []

// The Set object is added in ES6
var set = new Set()
set // Set(0) {}[[Entries]]No propertiessize: (...) __proto__: Set
Array.from(set) / / []
Copy the code

2, array.from () also provides a callback function similar

var arr = {
    '0': 'a'.'1': 'b'.'2': 'c'.length: 3
let arr = Array.from(arr,(i,n) = > {
   // The callback function is similar to => {... })
Copy the code

The array.of () array.of method is used to convert a set of string values to an Array

Array.of(1.2.3) / / [1, 2, 3]
Array.of(1) / / [1]
Array.of(1).length / / 1
Copy the code

Entries (), keys(), and values() are often used to traverse an array instance. Can be used for… Of loop traversal

for (let index of ['a'.'b'].keys()) {
/ / 0
/ / 1
Copy the code

Keys () is traversal of key names, values() is traversal of key values, and entries() is traversal of key-value pairs.

An operator…

let arr = []  
console.log(... arr)// 1, 2, 3, 4
// Merge the array
let arr2 = [5]
let concat = [...arr,...arr2] // (5) [1, 2, 3, 4, 5] 

// This is basically an array expansion operator
Copy the code

Extension of a function

Default values for function arguments

// Use the official example
function log(x, y = 'World') {
  console.log(x, y);
log('Hello') // Hello World
log('Hello'.'China') // Hello China
log('Hello'.' ') // Hello
Copy the code


// Use the official example
var x = 1;
function f(x, y = x) {
f(2) / / 2
// When the function f is called, the variable x has its own scope
// follow y = x
// Then print y to output 2
Copy the code

Let’s do the other one

let x = 1;
function f(y = x) {
  let x = 2;
f() / / 1

// Declare x globally
// function f assigns x to y by default, where x = 1;
// declare local variable x inside function f
// Print y, y equals the default value x, fixed output 1
// If global x is not declared, then an error is reported
Copy the code

Arrow function

Anyone who has used the Vue/React framework has used the arrow function concept. Let’s look at a simple example

var f = () = > 5;
/ / is equivalent to
var f = function () { return 5 };
var sum = (num1, num2) = > num1 + num2;
/ / is equivalent to
var sum = function(num1, num2) {
  return num1 + num2;
Copy the code

It’s actually a shorthand for an ES5 function to make the syntax simpler and clearer. Let’s look at it through an example

let getNumber= num= > ({ num: num, name: "tom" });
// Convert to ES5
var getNumber = function (num) {
	return {
		 num: num, 
		 name: "tom"}}// Note that if you want to return an object directly, you must enclose () parentheses, otherwise an error will be reported
Copy the code

1. The “this” object in the body of the function refers to the object that was defined, not the object that was used. In fact, there is no concept of this in the arrow function, so the direction of this in the arrow function does not change. 2, cannot be used as a constructor, that is, cannot use the new command, otherwise an error will be thrown. 3. Do not use arguments. This object does not exist in the function body. If you want to use rest (added in ES6)

Object extension

ES6 allows you to write variables and functions as properties and methods of an object directly inside curly braces. This writing is more concise.


const x = 'x';
const y = {x};
y // {x: "x"}

/ / is equivalent to
const y = {x: x};
Copy the code


function f(x, y) {
  return {x, y};
/ / is equivalent to
function f(x, y) {
  return {x: x, y: y};
f(1.2) // Object {x: 1, y: 2}
Copy the code

Property traversal mode

ES6 has five methods to traverse the properties of an object

/ / the commonly used
for. in// for... The in loop iterates over the object's own and inherited enumerable attributes (excluding the Symbol attribute).
// object. keys returns an array containing the keys of all the enumerable properties of the Object itself (not inherited), but not the Symbol property.

// Not commonly used
/ / Object. GetOwnPropertyNames returns an array that contains all attributes of the Object itself (excluding Symbol attribute, but cannot be enumerated attribute) of keys.
/ / Object. GetOwnPropertySymbols returns an array that contains all the Symbol attribute of the Object itself the key name.
// reflect.ownkeys returns an array containing all the key names of the object itself, whether the key names are Symbol or string, and whether they are enumerable or not.
Copy the code

Set, Map Data structure

Set ES6 provides a new data structure, Set. It’s like an array, but the values of the members are unique, there are no duplicate values, so let’s recognize it

const s = new Set(a); sSet(0) {}
No properties
size: (...).__proto__: Set
Copy the code

The add method, used to add an element

Set(1) {1}
Set(1) {1}[[Entries]] 
0: 1 
size: (...).__proto__: Set
// We can see that the s object has a data_0:1
Copy the code

When a value is added to a Set, the cast does not occur.

An array deset function can accept an array of values

const set = new Set([]);
set // Set(4) {1, 2, 3, 4}
0: 1
1: 2
2: 3
3: 4
size: (...).__proto__: Set
Copy the code

You can see that a set returns an object that looks like an array, so how do you convert it to a real array format and there are two ways that ES6 can do that, as we’ve seen above

const set = new Set([]);
[...set] // [1, 2, 3, 4]
Array.from(set) // [1, 2, 3, 4]
Copy the code

Properties and methods of the Set instance

Set. The prototype. The constructor: constructor, the default is Set function. Set.prototype.size: Returns the total number of members of the Set instance. The methods of a Set instance fall into two broad categories: operation methods (for manipulating data) and traversal methods (for traversing members). Here are four methods of operation.

Set.prototype.add(value) : Adds a value, returning the Set structure itself. Set.prototype.delete(value) : deletes a value. A Boolean value is returned to indicate whether the value is successfully deleted. Set.prototype.has(value) : Returns a Boolean value indicating whether the value is a member of a Set. Set.prototype.clear() : clears all members. No value is returned.


JavaScript objects are essentially collections of key-value pairs (Hash structures), but traditionally only strings can be used as keys, which limits their use.

In fact, Map deconstruction is similar to Set, so let’s get to know the Map structure

const m = new Map(a); mMap(0) {} 
No properties
size: (...).__proto__: Map
Copy the code

The method of adding and deleting Map data structure

// Use the official example
const m = new Map(a);const o = {p: 'Hello World'};
m.set(o, 'content')
m.get(o) // "content"

m.has(o) // true
m.delete(o) // true
m.has(o) // false
Copy the code

The above code uses the set method of the Map structure to treat the object o as a key of m, then reads the key using the get method, and then deletes the key using the delete method.

Map data destructor can also take an array as an argument, such as:

const map = new Map([['name'.'Joe'],
  ['title'.'Author']]); map.size/ / 2
map.has('name') // true
map.get('name') // "Zhang SAN"
map.has('title') // true
map.get('title') // "Author"
Copy the code

You pass an array as an argument, and all you’re doing is doing one iteration, new Map multiple times

const items = [
  ['title'.'Author']].const map = new Map(a); items.forEach(([key, value]) = > map.set(key, value)
Copy the code

So what’s different about Map? What problem does Map solve

const aa = new Map(a); aa.set({obj:'obj key-value pair equivalent key'},"123")
Map(1){{... } = >"123"}
0: {Object= > "123"}
key: {obj: "Obj key-value pair equivalent key"} / / the key the key
value: "123" / / key value
size: (...).__proto__: Map
Copy the code

Official explanation:

JavaScript objects are essentially collections of key-value pairs (Hash structures), but traditionally only strings can be used as keys, which limits their use.

Map solution: To solve this problem, ES6 provides a Map data structure. It is similar to an object in that it is also a collection of key-value pairs, but the range of “keys” is not limited to strings, and all types of values (including objects) can be used as keys. In other words, the Object structure provides a “string value” correspondence, and the Map structure provides a “value value” correspondence, which is a more complete implementation of the Hash structure.

Map instance properties and methods

Map.prototype.set(key, value) The set method sets the key value corresponding to key to value and returns the entire Map structure. If the key already has a value, the key value is updated, otherwise the new key is generated. Map.prototype.get(key) The get method reads the key corresponding to the key. If the key cannot be found, undefined is returned.

The map.prototype. has(key) has method returns a Boolean value indicating whether a key is in the current Map object.

Map.prototype.delete(key) The delete method removes a key, returning true. If deletion fails, return false.

The map.prototype.clear () clear method clears all members without returning a value.

Set: Obviously, we talked about the classic array demap: also obviously, with the key-value pair solved, the “key” can be a variety of types


Proxy can be understood as that a layer of “interception” is set up before the target object, and the external access to the object must pass this layer of interception first. Therefore, it provides a mechanism to filter and rewrite the external access. The original meaning of the word Proxy is Proxy, used here to mean that it “proxies” some operation.

Let’s get to know proxy with an official example

var obj = new Proxy({}, {
  get: function (target, key, receiver) {
    console.log(`getting ${key}! `);
    return Reflect.get(target, key, receiver);
  set: function (target, key, value, receiver) {
    console.log(`setting ${key}! `);
    return Reflect.set(target, key, value, receiver); }});// The above code sets up a layer of interception on an OBj object and redefines the properties' get and set behavior

obj.a = 1
// VM888:7 setting a!
obj.a / / 1
// VM888:3 getting a!
// VM888:7 setting a!
obj.a / / 2
Copy the code

We can see that we intercepted obj.a’s unique write operation.

Var proxy = new proxy (target, handler); The new Proxy() parameter generates a Proxy instance, the target parameter indicates the target object to intercept, and the Handler parameter is also an object to customize the interception behavior. In this case, accessing the proxy is equivalent to accessing the target object, for example:

var target = {};
var handler = {};
var proxy = new Proxy(target, handler);
proxy.a = 'b';
target.a // "b"
Copy the code

Extended properties: Interception operations supported by the Proxy

get(target, propKey, receiver)
// Intercepts reading of object properties, such as and proxy['foo'].
set(target, propKey, value, receiver)
Foo = v or proxy['foo'] = v, and return a Boolean value.
has(target, propKey)
// Intercept the propKey in proxy operation and return a Boolean value.
deleteProperty(target, propKey)
// Intercept the delete proxy[propKey] operation and return a Boolean value.
/ / interception Object. GetOwnPropertyNames (proxy), Object. GetOwnPropertySymbols (proxy), Object. Keys (proxy) for... In loop that returns an array. This method returns the property names of all of the target Object's own properties, whereas object.keys () returns only the traversable properties of the target Object itself.
getOwnPropertyDescriptor(target, propKey)
/ / interception Object. GetOwnPropertyDescriptor (proxy, propKey), returns the attributes describe objects.
defineProperty(target, propKey, propDesc)
// Intercept object.defineProperty (proxy, propKey, propDesc), object.defineProperties (proxy, propDescs) and return a Boolean value.
// Intercept object.preventExtensions (proxy) and return a Boolean value.
// Intercept object.getProtoTypeof (proxy) and return an Object.
// Intercepts object.isextensible (proxy) and returns a Boolean value.
setPrototypeOf(target, proto)
// Intercept object.setPrototypeof (proxy, proto) and return a Boolean value. If the target object is a function, there are two additional operations that can be intercepted.
apply(target, object, args)
// Intercepts the operation of a Proxy instance as a function call, such as Proxy (... The args), proxy. Call (object,... The args), proxy. Apply (...). .
construct(target, args)
// Intercepts the operation of a Proxy instance as a constructor call, such as new Proxy (... The args).
Copy the code

The Generator function

Generator functions are an asynchronous programming solution provided by ES6 with a syntax behavior completely different from traditional functions.

Let’s start with Generator function 1. There is an asterisk between the function keyword and the function name. 2. Use yield expressions inside the function body to define different internal states

A Generator function is called in a slightly different way than a normal function. A normal function call is just fun(). A Generator function is called in a way that, which is fun().next(), to move the pointer to the next state; That is, each time the next method is called, the internal pointer is executed from the head of the function or where it stopped last, until the next yield expression (or return statement) is encountered. In other words, the Generator function is executed in segments, the yield expression is a marker to pause execution, and the next method can resume execution.

For those of you who have read my Javascript Advanced article 2, you should know that function currying is a bit similar to GO Javascript Advanced 2

Let’s look at a practical example

function* Gen () {
	yield 'Hi';
	yield 'Sen';
	return "HiSen";
var G = Gen()
{value: "Hi".done: false}
{value: "Sen".done: false}
{value: "HiSen".done: true}
{value: undefined.done: true}
Copy the code

The result is obvious: the variable G equals the function Gen(), and the g.ext () execution goes to the next state, returning an object at a time whose value property is the value of the current yield expression, and whose done property value is false, indicating that the traversal is not complete. {value: “HiSen”, done: true}} {value: undefined, done: true}} {value: undefined, done: true}} {value: undefined, done: true}}

To summarize, call the Generator function and return a traverser object that represents an internal pointer to the Generator function. Later, each time the next method of the traverser object is called, it returns an object with two properties, value and done. The value attribute represents the value of the current internal state and is the value of the expression following the yield expression; The done property is a Boolean that indicates whether the traversal is complete.

async await

What is an async function? In short, it is the syntactic sugar for Generator functions. Async and await have clearer semantics than asterisks and yields. Async means that there are asynchronous operations in the function, and await means that the following expression needs to wait for the result (an asynchronous task).

Basic usage: A function is preceded by the async keyword to indicate that there are asynchronous operations within the function. When you call this function, it immediately returns a Promise object that I’ll talk about later. Await is generally used inside async functions.

Let’s take a look at async functions with a simple example

async function as () {
	return 2;
as(a)// Promise {<resolved>: 2}
Copy the code

We can see that a promise object is returned and that the default resolved callback succeeds in passing parameter 2. We can conclude that the value returned by the return statement inside the async function will become the parameter of the then method callback.

Next, let’s get to know the await. Normally, the await command is followed by a Promise object that returns the result of that object. If it is not a Promise object, the corresponding value is returned. So let’s try it out

function setTime () {
	return new Promise(function (resolve,reject) {
			function () { 
setTime()  Return a Promise {
       } object

// await accepts a Promise object, which we isolate using the setTime function.
async function as () {
	var num = 1;
	num = await setTime(); // Await followed by a Promise object
as(a)// Promise {
       } return "Success" after 2 seconds
Copy the code

Analysis: The setTime function returns a promise object and calls resolve(” successful “) after 2 seconds. Then we define an async await function as. Await setTime() means to wait for the result of setTime() before proceeding 3, so it will print successfully after 2 seconds

A simple async await function appears in front of everyone. It is very simple and amazing, and the code looks completely synchronous. Declare variables, assign variables, print variables, but contain asynchronous tasks. The await command can be followed by Promise objects and primitive values (numeric, string, and Boolean), but this automatically converts to an immediately resolved Promise object.


What is a Promise object? Promise is a solution to asynchronous programming that is more rational and powerful than the traditional solution callback function. ES6 writes it into the language standard, unifying usage and providing Promise objects natively. Check the Promise

Let’s start with the basics

// Create a Promise object
var promise=new Promise(function(resolve,reject){
   / /... some async code
   // Call resolve or reject based on the result of asynchrony

// Success and failure callbacks
  // error
Copy the code

Before we analyze it, we need to know how Promise works

Note that a Promise can only be in one state at a time

This parameter is fulfilled fulfilled. Pending: The execution is fulfilled

The state can only be changed from pending to Resolved or Rejected. Once the state change is complete, it cannot be changed (irreverability).

Fulfilled (Resolved) Pending —— “Fulfilled (resolved) pending——

Ok, now that we know how it works, let’s take a look at the code: After the asynchronous operation is complete, call Resolve and reject for different results.

Resolve and reject are two functions. Resolve is called when an asynchronous operation succeeds, passing the return value of the asynchronous operation as an argument. Reject is called when an asynchronous operation makes an exception, passing the error message as an argument.

After the asynchronous result is passed, use the THEN method to get the result returned by the asynchronous, which is promise.then(…) shown above. Is that clear, guys? The simple answer is: 1, define a promise object, do an asynchronous operation in it, get the result 2, call resolve or reject based on the result, make an asynchronous callback 3, and execute the corresponding callback

Of course, I believe that many children have seen in various blogs, forums, promise to deal with callback hell, in fact, the principle is very simple, is a successful callback chain call, a simple example.

var promise=new Promise(function(resolve,reject){
promise.then(res= > {
	return res;
}).then(res= > 
//  2 
Copy the code

The obvious result is that you need to return the last successful callback, and then the chain call is used all the time.


In ES6, class is a new class that can be inherited through the extends keyword, which is much cleaner and easier than ES5’s implementation of inheritance by modifying the prototype chain.

Get to know the class class

/ / class
class parent{}// Child inherits parent, which can be implemented directly on the console
class child extends parent{}typeof parent
// "function"
Copy the code

Class parent {} ES2015 function parent () {} ES2015 function parent () {

Let’s expand on that

/ / class
class parent{
	constructor(x, y) {
	    this.x = 1;
	    this.y = 2; }}// Child inherits parent, which can be implemented directly on the console
class child extends parent{
	constructor(x, y, z) {
	    super(x, y); Constructor (x, y) = constructor(x, y);
	    this.z= 3; }}Copy the code

Function parent (constructor(x,y) {this.x=x; constructor(x,y) {this.x=x; this.y=y; } This code should be familiar to anyone who has written react projects.

Super () Super represents the constructor of the superclass. ES6 requires that the constructor of a subclass must execute the super function once.

Module is briefly introduced here, and I will write a post on modularization later

CommonJS: For the Node.js environment

/ / export
module.exports = moduleA.func;
/ / import
const moduleA = require( url );
Copy the code

AMD: For node.js environment, browser. The asynchronous mode is home to the module -> requireJS

// Define the module
define( 'module'['dep'].function(dep) {
  return exports; })// Import the module
require(['module'].function(module) {})Copy the code

ES6 modularity: Needs to be converted to ES5 run

/ / export
export function  hello(){};
export default {};
/ / import
import { A } from url;
import B from url;
Copy the code

Welcome to like, a little encouragement, a lot of growth