This is the fourth day of my participation in the August More text Challenge. For details, see:August is more challenging

You know, ES6 is a must-learn for front-end development. This article is suitable for the initial introduction and review, and can further study ES6 with ruan yifeng’s tutorial.

Directory:

  1. Block level scope, block level let, block level constant const
  2. Arrow function
  3. Parameter processing (default parameter /…)
  4. Template literals (template strings)
  5. Object extension
  6. Deconstruction assignment
  7. Module (import/export)
  8. Class (class/extends)
  9. Promise
  10. End Thanks for reading

Block level scope, let, constant const

  1. Statements defined by a pair of {} statements are called block statements, which in other programming languages are called compound statements.

Generally understood blocks:

  • Block: contained by {}
  • If (){} : is a block
  • For (){} : is a block

These can also be understood as blocks:

  • A function: Function scope
  • The script tag: global scope
  1. JS variables declared with var have no block-level scope, only function scope and global scope.
var x = 1;
{
  var x = 2;
}
console.log(x);
Copy the code
  • 2 is printed because the var statement in the block has the same scope as the var statement preceding the block
  • In C or Java, this code would print 1
  • This code proves that var has no block scope
  1. In contrast, variables declared with let and const are block-scoped.
let x = 1;
{
  let x = 2;
}
console.log(x); 
Copy the code
  • Output 1
  • X is limited to block-level scope
  • The same thing happens here if we change let to const
  1. The classic example (Back to live) :
var a = [];
for (var i = 0; i < 10; i++) {
      a[i] = function () {console.log(i); }; } a[0] ();/ / 10
a[1] ();/ / 10
a[6] ();/ / 10

/ * * * * * * * * * * * * * * * * * * * * /

var a = [];
for (let i = 0; i < 10; i++) {
      a[i] = function () {console.log(i); }; } a[0] ();/ / 0
a[1] ();/ / 1
a[6] ();/ / 6
Copy the code
  • The I in the first one has no block-level scope, there is only one global variable I, and the code in each {} loop refers to the same I
  • The I in the second is block-scoped, and the current I is valid only for the current round of the loop. The code in the {} of each loop refers to a different I
  • It is worth noting that () for is a parent scope and {} is a child scope
  • Because the current I is only valid for the round, the let definition of I is redefined each time, each time with a new variable
  1. Supplement:

There is also block-level scope when using function:

foo('outside');  // TypeError: foo is not a function
{
  function foo(location) {
   console.log('foo is called ' + location);
  }
  foo('inside'); // Works properly and prints 'foo is called inside'
}
Copy the code
  1. Var variable is promoted, let variable is temporarily dead:
console.log(foo); // Output undefined without an error
var foo = 2; 

console.log(bar); / / error ReferenceError
let bar = 2;
Copy the code
  • Var can be promoted to the top of the function or the global
  • Let does not have this situation, and must be called after the let declaration (const is the same as let).
  • This phenomenon of let and const is called a temporary dead zone
  • There is a “temporary dead zone” between the start of the block and the let declaration
  1. Let the wrong

Repeating a variable in the same scope with a let will raise TypeError

if (x) {
  let foo;
  let foo; // TypeError thrown
}
Copy the code
  1. The concept of const
  • Its value must be specified in the same statement as the declaration
  • A const declaration creates a read-only reference to a value. That is, the value can only be read through a variable defined as const, not modified, but if the value itself changes, the value of the variable defined as const changes as well, such as when the object is invoked.
  • A constant cannot have the same name as any other variable or function in its scope.
// Constants require an initial value
const FOO;

// Constants can be defined as objects
const MY_OBJECT = {"key": "value"};
// The following error, changing the constant will fail
MY_OBJECT = {"OTHER_KEY": "value"};
// The object properties are not in the scope of the protection, the next successful execution (object itself changed)
MY_OBJECT.key = "otherValue";

// Define a constant
const MY_FAV = 20;
// It cannot be the same name
var MY_FAV = 20; 
// Error will also be reported
let MY_FAV = 20;
Copy the code

Two. Arrow function

Basic grammar:

// General syntax:(parameter1, the parameter2,... , parameter N) => {function declaration}// equivalent to :(parameter 1, parameter 2... , parameter N) =>{return expression; }(parameter1, the parameter2,... , parameter N) => Expression (single)// Parentheses are optional when there is only one argument:=> {function declaration} => {function declaration}// Functions with no arguments should be written in parentheses() => {function declaration}Copy the code

Advanced grammar:

Note: Literals are usually constructed as [1, 2, 3] or {name: “MDN “}

// The parenthesized body of the function returns the literal expression of the object:Parameter = > ({foo: bar})

// Support the remaining parameters and default parameters(parameter1, the parameter2. Rest) => {function declaration} (parameter1= default values1, the parameter2,... , parameter N = default value N) => {function declaration}// Argument list deconstruction is also supported
let f = ([a, b] = [1.2], {x: c} = {x: a + b}) = > a + b + c;
f();  / / 6
Copy the code

Example:

Arrow functions are useful where anonymous functions are needed, such as in the callback to the array’s built-in map, Filter, forEach, and Reduce methods

var elements = [
  'Hydrogen'.'Helium'.'Lithium'.'Beryllium'
];

elements.map(function(element) { 
  return element.length; 
}); // Return array: [8, 6, 7, 9]

// The above normal function can be rewritten as the following arrow function
elements.map((element) = > {
  return element.length;
}); // [8, 6, 7, 9]
Copy the code

Important note:

The point of the this object is mutable, but in the arrow function, it is fixed. The this object in the body of the arrow function is the object that was defined, not the object that was used.

3. Parameter processing

  1. Set default parameter values for the function

Before ES6, we wanted to set parameters by default and it was worth doing:

function multiply(a, b) {
  // The default argument to a function in JavaScript is undefined
  // Give b a default value when no value is passed or undefined is passed to b
  b = (typeofb ! = ='undefined')? b :1;
  return a * b;
}

multiply(5.2); / / 10
multiply(5);    / / 5
Copy the code

Now that you’ve learned ES6, it’s easy:

function multiply(a, b = 1) {
  return a * b;
}

multiply(5.2); / / 10
multiply(5);    / / 5
Copy the code

Note that the arguments are passed from left to right:

function f(x = 1, y) { 
  return [x, y]; 
}

f(); // [1, undefined]
f(2); // [2, undefined]
Copy the code
  1. Remaining parameters (…)

The remaining arguments syntax allows us to represent an indefinite number of arguments as an array.

Grammar:

function(a, b, ... theArgs) {... }Copy the code
  • Must be the last argument to the function to… The prefix
  • It is an Array consisting of the remaining arguments
  • TheArgs in this example collects the third argument and all subsequent arguments

Example:

function fun1(. theArgs) {
  alert(theArgs.length); // All array property methods can be used
}
fun1();  // Pop "0" because theArgs has no element
fun1(5); // Pop "1" because theArgs has only one element
Copy the code
  1. Expansion operator (…)

An array expression or string can be expanded syntactically during a function call/array construction. You can also expand an object expression as a key-value when constructing a literal object.

Note: Literals are usually constructed as [1, 2, 3] or {name: “MDN “}

  • Use expansion syntax for function calls:
function sum(x, y, z) {
  return x + y + z;
}
const numbers = [1.2.3];
console.log(sum(... numbers));/ / 6

/**** In the following example, ****/ can be used multiple times

function myFunction(v, w, x, y, z) {}var args = [0.1];
myFunction(-1. args,2. [3]);
Copy the code
  • Use expansion syntax when constructing an array of literals:
/**** constructs an array of literals or a concatenation array ****/
var parts = ['shoulders'.'knees']; 
var lyrics = ['head'. parts,'and'.'toes']; 
// ["head", "shoulders", "knees", "and", "toes"]
var arr = [...parts, ...lyrics];

/**** Shallow copy (one-dimensional array)****/ is supported
var arr = [1.2.3];
var arr2 = [...arr];
arr2.push(4); 
// arR2 = [1, 2, 3, 4]
// ArR is not affected
Copy the code
  • Use expansion syntax when constructing literal objects:
var obj1 = { foo: 'bar'.x: 42 };
var obj2 = { foo: 'baz'.y: 13 };

varclonedObj = { ... obj1 };/ / shallow copy
// Clone object: {foo: "bar", x: 42}

varmergedObj = { ... obj1, ... obj2 };{foo: "baz", x: 42, y: 13}
Copy the code

Iv. Template literals (template strings)

Replace single ” or double ‘”” with backquote ”.

  • One-line string:
`string text`
Copy the code
  • Multiline strings (note that carriage returns are included)

No longer concatenate two lines of string with “+” or “\”

`string text line 1 string text line 2`

console.log(`string text line 1
string text line 2`);
Copy the code
  • Insert expression:

No more joining expressions with “+”

`string text ${expression} string text`

var a = 5;
var b = 10;
console.log(`a + b is ${a + b}`);
Copy the code
  • Labeled template strings:

The tag allows us to parse the template string using a function.

Look directly at the example:

var person = 'Mike';
var age = 28;

function myTag(strings, personExp, ageExp) {

  var str0 = strings[0]; // "that "
  var str1 = strings[1]; // " is a "

  var ageStr;
  if (ageExp > 99){
    ageStr = 'centenarian';
  } else {
    ageStr = 'youngster';
  }

  return str0 + personExp + str1 + ageStr;
}

var output = myTag`that ${ person } is a ${ age }`;

console.log(output);
// that Mike is a youngster
Copy the code
  • Raw string:

In the first argument to the tag function, there is a special attribute called RAW that allows us to access the original string of the template string without special character replacement.

Example:

function tag(strings) {
  console.log(strings.raw[0]);
}
tag`string text line 1 \n string text line 2`;
// logs "string text line 1 \n string text line 2"
Copy the code

5. Object extensions

  • You can simplify methods and key-value pairs with the same name when creating objects

General information:

var name="pan";
var age=20;
var people = {
      name: name,
      age: age,
      getName: function() {
           console.log(this.name)
      }
};
Copy the code

ES6 simplified:

var name="pan";
var age=20;
var people = {
      name,
      age,
      getName(){
           console.log(this.name)
      }
};
Copy the code
  • Evaluate attribute names (attribute names can be expressions)
var i = 0;
var a = {
  ["foo" + ++i]: i,
  ["foo" + ++i]: i,
  ["foo" + ++i]: i
};
console.log(a.foo1); / / 1
console.log(a.foo2); / / 2
console.log(a.foo3); / / 3
Copy the code
  • proto

When the property: value defined is a PROto: value, the property named proto is not created. But when the value is an object, the stereotype is changed (because proto originally points to the stereotype). Therefore, it is not recommended to use this property name (to avoid changing the point to proto).

Vi. Deconstruct assignments

Deconstructive assignment syntax is a JavaScript expression that makes it possible to extract values from arrays, or properties from objects, into different variables.

The goal is to easily extract values from an array or attributes from an object into other variables

  • Deconstruct array syntax:
var x, y;
[x, y] = [1.2.3];
console.log(x); / / 1
console.log(y); / / 2

/ / or:
var [x, y] = [1.2.3];
console.log(x); / / 1
console.log(y); / / 2
Copy the code

Tips (swapping variables without temporary variables) :

var a = 1;
var b = 3;
// equivalent to [a,b]=[3,1]
[a, b] = [b, a];
console.log(a); / / 3
console.log(b); / / 1
Copy the code
  • Deconstruct object syntax:
var o = {p: 42.q: true};
var {p, q} = o;

console.log(p); / / 42
console.log(q); // true
Copy the code

Note that object destructuring differs from array destructuring in one important way. The elements of an array are arranged in order, and the value of a variable is determined by its position. The properties of an object have no order, and the variable must have the same name as the property in order to get the correct value.

Module (import/export)

The module function consists of two commands: export and import. The export command is used to specify the external interfaces of a module. The import command is used to enter the functions provided by other modules.

A module is a separate file. All variables inside this file are not available externally. If you want a variable inside the module to be read externally, you must export the variable using the export keyword. Below is a JS file that uses the export command to output variables.

  • Export export
// profile.js
var firstName = 'Michael';
var lastName = 'Jackson';
var year = 1958;

export {firstName, lastName, year};
Copy the code
  • The code above is a profile.js file that holds user information,
  • ES6 treats it as a module that outputs three variables externally using the export command.
  • In addition to this ordinary variable, the output variable can also be a function.
  • In addition, the interface output by the export statement is dynamically bound to its corresponding value.
  • That is, through this interface, you can get the real-time value inside the module.
  • Finally, the export/import command cannot be in block-level scope, but can be anywhere in global scope.
  • Import the import

Import statements can only be used in tags that declare a script of type=”module”. Dynamic import: import(), which does not depend on the script tag of type=”module”. Dynamic import() is useful when loading modules under certain conditions or on demand. Static import is the best choice for initial loading.

// main.js
import {firstName, lastName, year} from './profile.js';

function setName(element) {
  element.textContent = firstName + ' ' + lastName;
}
Copy the code
  • The import command of the above code is used to load the profile.js file and enter variables from it.
  • The import command accepts a pair of curly braces that specify the name of a variable to be imported from another module.
  • The variable name in the braces must be the same as the name of the external interface of the imported module (profile.js).

Note: The import statement executes the loaded module:

import './lodash.js';
// Execute the lodash module, but enter no values
Copy the code

Overall import:

import * as myModule from './my-module.js'; // Do not open brackets {}
// Let the my-module output variables/functions,
// Input to the object myModule as a property/method.
// By myModule. attribute name/myModule. Method () is called.
Copy the code
  • Default Export/Import Default values:

When using the import command, the user needs to know the status of the name of the variable or function to be loaded:

// Use the export default syntax to export by default
// This is the default output, so a template can only be used once
export default function foo() {
  console.log('foo');
}

// Import the default values
import customName from './default.js'; // Do not open brackets {}
customName(); // 'foo'
Copy the code

Class eight.

The JavaScript classes introduced in ES6 are essentially syntax sugar for JavaScript’s existing prototype-based inheritance. Class syntax does not introduce a new object-oriented inheritance model to JavaScript.

  • How to create a class:
class Rectangle {
  constructor(height, width) { // The constructor
    this.height = height;
    this.width = width; }}/ / or
let Rectangle = class {
  constructor(height, width) { // The constructor
    this.height = height;
    this.width = width; }};Copy the code
  • How to use classes:
class Rectangle {
    // constructor
    constructor(height, width) {
        this.height = height;
        this.width = width;
    }
    // Getter
    get area() {
        return this.calcArea()
    }
    // Method
    calcArea() {
        return this.height * this.width; }}const square = new Rectangle(10.10);

console.log(square.area); / / 100
Copy the code
  • Class static methods:

Static methods cannot be called from a class instance (this is different from Java syntax)

class Point {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }

    static distance(a, b) { / / the static grammar
        const dx = a.x - b.x;
        const dy = a.y - b.y;

        return Math.hypot(dx, dy); }}const p1 = new Point(5.5);
const p2 = new Point(10.10);
// Called directly by the class name
console.log(Point.distance(p1, p2));
Copy the code
  • Inheritance of a class (extends)
class Animal { 
  constructor(name) {
    this.name = name;
  }
  
  speak() {
    console.log(this.name + ' makes a noise.'); }}class Dog extends Animal {
   constructor(name) {
    super(name); // Call the superclass constructor
  }

  speak() {
    console.log(this.name + ' barks.'); }}var d = new Dog('Mitzie');
// 'Mitzie barks.'
d.speak();
Copy the code
  • Calling a superclass method (super)
class Cat { 
  constructor(name) {
    this.name = name;
  }
  
  speak() {
    console.log(this.name + ' makes a noise.'); }}class Lion extends Cat {
  speak() {
    super.speak();
    console.log(this.name + ' roars.'); }}Copy the code

9. Promise objects

This part of the content is the key and difficult point, it is not too much to say that the interview test knowledge point, because it is not easy to simple summary, so I recommend the friends who read here to read Ruan Yifeng Promise, systematically study this part of the content.

Thank you for reading

Leave precious praise before you go!