ES6

ES6 syntax basics

The let command

  • The basic grammar

    ES6 added the let command to declare variables. Its use is similar to var, except that the variables declared by the let command are only valid within the block of code in which the let command resides.

  • There is no variable promotion

    Unlike var, let does not have the phenomenon of “variable promotion”.

  • Temporary dead zone

    As long as the let command exists in the block-level scope, the variables it declares are in the “binding” area, no longer subject to external influence.

  • Duplicate declarations are not allowed

    Let does not allow the same variable to be declared twice in the same scope.

Block-level scope

  • Why do you need block-level scopes?

    ES5 has only global and functional scopes, not block-level scopes, which leads to a lot of irrational scenarios.

    Scenario 1: An inner variable may override an outer variable.

    The second scenario: loop variables used to count are leaked as global variables.

  • ES6 block-level scope

    Let actually adds block-level scope to JavaScript.

Execute function immediately

(function () {} ());Copy the code

Const command

Const is also used to declare variables, but only constants. Once declared, the value of a constant cannot be changed. Const declared constants are valid only for the current code block.

Declare a frozen object (that is, the value of an object’s member variables cannot be changed)

const person = Object.freeze({
  name: "zhangsan".age: 20
});
Copy the code

A function that freezes an object completely

freeze.js

var constantize = (obj) = > {
  Object.freeze(obj);
  Object.keys(obj).forEach((key, value) = > {
    if(typeof obj[key] === 'object') { constantize(obj[key]); }})};Copy the code

Cross module constant

moduleA.js

export const HOST = "http://www.xxx.com";
export const PORT = 8080;
export const NAME = "Lark"; How do I use the HOST constant in moduleB.js in moduleA.js? moduleB.js// * Indicates all imports
import * as ma from "./moduleA";
// Use variables in moduleA like this
console.log(ma.HOST);

// Partial import
import { HOST, PORT } as ma from "./moduleA";

console.log(ma.HOST, ma.PORT);

// Import only one
import NAME as ma from "./moduleA";

console.log(ma.NAME);
Copy the code

Properties of a global object

A global object is the top-level object, which in the browser environment is the Window object and in Node.js is the global object. In JavaScript, all global variables are properties of the global object. (Node is a special case; this applies only to REPL environments, where modules must be explicitly declared as global properties.)

ES6 specifies that global variables declared by var and function commands are attributes of global objects. Global variables declared by the let, const, and class commands are not properties of the global object.

Such as:

var varName = "varValue";

// in the browser environment
console.log(window.varName);
// node.js
console.log(global.varName);
// In the general environment
console.log(this.varName);
Copy the code

Structure assignment

Array structure assignment

  • Destructuring

    ES6 allows you to extract values from arrays and objects and assign values to variables in a pattern called Destructuring.

  • Incomplete deconstruction

    The pattern to the left of the equals sign matches only part of the array to the right of the equals sign.

  • Specify default values

    Note: ES6 internally uses the strict equality operator (===) to determine whether a position has a value. Therefore, if an array member is not strictly equal to undefined, the default value will not take effect.

  • Let and const commands

    Any data structure that has an Iterator interface can be assigned in the form of an array.

// Destructuring
// ES6
var [a, b, c] = [1.2.3];
console.log(a, b, c);/ / 1 2 3

// Not completely deconstructed
var [first, second] = [1];
console.log(first); / / 1
console.log(second); //undifined

// Specify a default value
var [one = "One", two] = [];
console.log(one); // One
console.log(two); // undefined

var [x = "abc", y] = [undefined."xyz"];
console.log(x); // ABC is not overwritten because undefined means there is no value
console.log(y); //xyz

/ / the iterator interface
let [a, b, c] = new Set(["a"."b"."c"]);
console.log(a); //a
console.log(b); //b
console.log(c); //c

function* fibs() {
    let a = 0;
    let b = 1;
    while(true) {
        yield a;
        [a, b] = [b, a + b];
    };
    var [first, second, third, fourth, fifth, sixth] = fibs();
    console.log(sixth); / / 5
}
Copy the code

Object destructuring assignment

  • Deconstruction can be applied to objects as well as arrays

    The attributes of an object have no order, and variables must have the same name as the attributes to get the correct value.

  • Specify default values

    Default values are valid only if the property value of the object is strictly undefined (that is, if there is a value, the default value does not take effect).

  • Methods of existing objects

    Destruct assignment of an object makes it easy to assign the methods of an existing object to a variable.

var {name, age} = {name: "Lark".age: 30};
console.log(name, age); // Lark 30
Copy the code

What if the variable name and attribute name do not match?

var {name: pName, age: pAge} = {name: "Lark".age: 30};
console.log(pName, pAge); // Lark 30
Copy the code

Specify default values

var { x = 3 } = {};

console.log(x); / / 3

var { y = 4 } = { y = undefined };
console.log(y); / / 4

var { z = 5 } = { z = null };
console.log(z); // null
Copy the code

Destruct assignment of a declared variable

var x;
{ x } = { x: 1 };
console.log(x); // Error syntax, failed to compile

var y;
({ y } = { y: 1 });
console.log(y); / / 1
Copy the code

Methods of existing objects (use methods of existing objects instead of every object. Method method called)

let { sin, cos, tan, PI } = Math;
console.log(sin(PI / 6)); / / 0.49999999
Copy the code

Destruct assignment of a string

  • Strings can also deconstruct assignments

    The string is converted to an array-like object

  • Attribute destruct assignment

    Array-like objects have a length attribute, so you can also deconstruct and assign to this attribute.

var { a, b, c, d, e } = "hello";
console.log(a, b, c, d, e); // h e l l o
Copy the code

Attribute deconstruction of a string

const { length: len } = "hello";
console.log(len); / / 5
Copy the code

Destruct assignment of function arguments

  • Function arguments can also be destructed
  • Function arguments can also be destructed using default values

Destruct assignment of function arguments

function sum([x, y]) {
    return x + y;
}
console.log(sum([1.3])); / / 4
Copy the code

Function arguments destruct the default value of assignment

function sum({x = 0, y = 0} = {}) {
    return [x, y];
}
console.log(sum({x: 100.y: 200})); / / [100, 200]
console.log(sum({x: 100})); / / [100, 0]
console.log(sum({})); / / [0, 0]
console.log(sum()); / / [0, 0]
Copy the code
function sum({x, y} = {x: 0, y: 0}) {
    return [x, y];
}
console.log(sum({x: 100.y: 200})); / / [100, 200]
console.log(sum({x: 100})); // [100, undefined]
console.log(sum({})); // [undefined, undefined]
console.log(sum()); {x, y} = {x: 0, y: 0} will be executed in the function.
Copy the code

Deconstruct the purpose of assignment

  • Swap the values of variables
  • Returns multiple values from a function
  • Definition of function parameters
  • Extracting JSON data
  • Default values for function arguments
  • Traverse map deconstruction
  • Specifies the method of input module

Swap the values of variables

var x = 100;
var y = 200;
[x, y] = [y, x];
console.log(x, y); / / 200 100
Copy the code

Returns multiple values from a function

function fun() {
    return [1.2.3];
}
var [x, y, z] = fun();
console.log(x, y, z); / / 1 2 3
Copy the code
function fun() {
    return {
        id: "001".name: "Lark".age: 30
    };
}
var { id, name, age } = fun();
console.log(id, name, age); // 001 Lark 30
Copy the code

Definition of function parameters

// Arguments are an ordered set of values
function fun([x, y, z]) {
    // x=100 y=200 z=300
}
fun([100.200.300]);

// Arguments are an unordered set of values
function fun2({id, name, age}) {
    // id="001" name="Lark" age=30
}
fun2({id: "001".name: "Lark".age: 30});
Copy the code

Extracting JSON data

var jsonData = {
    id: "001".name: "Lark".age: 30.score: {
        Chinese: 100.English: 90}};let { id, name, age, score } = jsonData;
console.log(id, name, age, score);// 001 Lark 30 
Copy the code

Default values for function arguments

jQuery.ajax({
    url: '/path/to/file'.type: 'POST'.dataType: 'xml/html/script/json/jsonp'.data: {param1: 'value1'},
    complete: function(xhr, textStatus) {},success: function(data, textStatus, xhr) {},error: function(xhr, textStatus, errorThrown) {}}); jQuery.ajax =function(url, { async = true, beforeSend = function() {},
    cache = true,
    complete = function() {},
    crossDomain = false,
    global = true{})// do something
};
Copy the code

Traverse map deconstruction

var map = new Map(a); map.set("id"."001");
map.set("name"."Lark");
map.set("age".30);

// Get the key name and value
for(let [key, value] of map) {
    console.log(key, value);
}
// id 001
// name Lark
// age 30

// Get the key name
for(let [key] of map) {
    console.log(key);
}
// id
// name
// age

// Get the key value
for(let [, value] of map) {
    console.log(value);
}
/ / 001
// Lark
/ / 30
Copy the code

Specifies the method of input module

const { SourceMapConsumer, SourceNode } = require("source-map");
Copy the code





We will keep you updated. See you at……