ES6 Chinese Handbook

Source: Internet
Author: User
Tags time and date

This is a ES2015 (ES6) Cheatsheet, which includes hints, tips, best practices, and some code snippets to help you
Complete day-to-day development work. Table of Contents var and let/const declaration code execution Block Replace immediate execution function arrow function string Deconstruction module parameter class symbols Maps Weakmaps promises generator S Async Await
var versus let/const

In addition to Var, we now have two new identifiers that declare the storage of variables, which are let and Const.
Unlike Var, let and const statements do not cause a claim elevation.

Example of a var:

var snack = ' Meow Mix ';

function Getfood (food) {
    if (food) {
        var snack = ' friskies ';
        return snack;
    }
    return snack;
}

Getfood (FALSE); Undefined

Let's look at the following statement, which replaces the performance of Var with let:

Let snack = ' meow Mix ';

function Getfood (food) {
    if (food) {let
        snack = ' friskies ';
        return snack;
    }
    return snack;
}

Getfood (FALSE); ' Meow Mix '

When we refactor the old code that uses VAR, we must pay attention to this change. Blindly using let to replace Var may result in unexpected unintended results.

Note : Let and const are block-level scope statements. So referencing these variables outside of the statement block results in a reference error referenceerror.

Console.log (x);

Let x = ' Hi '; REFERENCEERROR:X is not defined

Best Practice : When refactoring old code, the Var declaration requires extra attention. When creating a new project, use let to declare a variable, using const to declare an immutable constant.

(Back to catalog) replacing iifes with Blocks

When we used to create an immediate execution function , we usually wrap a bracket around the outermost layer of the function.
ES6 supports block-level scopes (closer to other languages), we can now do this by creating a block of code that doesn't have to be created by creating a function.

(function () {
    var food = ' Meow Mix ';
} ());

Console.log (food); Reference Error

Use a version of ES6 that supports block-level scopes:

{Let
    food = ' Meow Mix ';
}

Console.log (food); Reference Error

(Back to catalog) Arrow Functions

Some times we need to access this in the context of a function nesting. For example, the following examples:

function person (name) {
    this.name = name;
}

Person.prototype.prefixName = function (arr) {return
    arr.map (function (character) {return
        THIS.name + Character Cannot read property ' name ' of undefined
    });

A common way is to keep this in a variable in the context:

function person (name) {
    this.name = name;
}

Person.prototype.prefixName = function (arr) {
    var that = this;//Store The context of this return
    Arr.map (func tion (character) {return
        that.name + character;
    });

We can also pass this through the attributes:

function person (name) {
    this.name = name;
}

Person.prototype.prefixName = function (arr) {return
    arr.map (function (character) {return
        THIS.name + character;
    }, this);

You can also use bind directly:

function person (name) {
    this.name = name;
}

Person.prototype.prefixName = function (arr) {return
    arr.map (function (character) {return
        THIS.name + Character
    }. Bind (this));

Use the arrow function , this value does not need us to do as the last few pieces of code special treatment, direct use.
The above code can be rewritten as follows:

function person (name) {
    this.name = name;
}

Person.prototype.prefixName = function (arr) {return
    arr.map (character => this.name + character);

Best Practice : Use the arrow function, no longer consider this issue.

When we write a simple function that returns only one expression value, you can also use the arrow function as follows:

var squares = Arr.map (function (x) {return x * x}); Function Expression
Const ARR = [1, 2, 3, 4, 5];
Const SQUARES = arr.map (x => x * x); Arrow Function for Terser implementation

Best Practice : Use the arrow functions as much as possible.

(Back to catalog) Strings

In ES6, the standard libraries are also enhanced, like String objects. Includes () and. Repeat () methods. . Includes ()

var string = ' food ';
var substring = ' foo ';

Console.log (string.indexof (substring) >-1);

Now, we can use the. Inclues () method to replace the previous >-1 way of judging content.
The. Includes () method returns a Boolean result in a very simple way.

Const string = ' food ';
Const SUBSTRING = ' foo ';

Console.log (string.includes (substring)); True
. Repeat ()
function Repeat (string, count) {
    var strings = [];
    while (Strings.length < count) {
        Strings.push (string);
    }
    Return Strings.join (");
}

In ES6, we can use a minimalist method to implement repeating characters:

String.repeat (numberofrepetitions)
' Meow '. Repeat (3);//' Meowmeowmeow '
Template Literals

Using string template literals , I can use special characters directly in a string without escaping.

var text = "This string contains \" Double quotes\ "which are escaped.";
Let-text = ' This string contains ' double quotes ' which don ' t need to be escaped anymore. '

string Template literals also support the direct insertion of a variable, which enables the direct connection output of a string and a variable.

var name = ' Tiger ';
var age =;

Console.log (' My cat are named ' + name + ' + ' + ' + ' + ' + ' + Age + ' years ');

Simpler version:

Const NAME = ' Tiger ';
Const AGE =;

Console.log (' My cat is named ${name} and are ${age} years old. ')

In ES5, we want to generate multiple lines of text like this:

var text = (
    ' cat\n ' + '
    dog\n ' + '
    Nickelodeon '
);

Or:

var text = [
    ' cat ',
    ' dog ', '
    Nickelodeon '
].join (' \ n ');

string Template literals let us not pay special attention to the newline escape symbol in a multiline string, which can be wrapped directly:

Let text = (' Cat
dog
Nickelodeon '
);

string Template literals you can use an expression internally, like this:

Let today = new Date ();
Let-text = ' The time and date is ${today.tolocalestring ()} ';

(Back to catalog) destructuring

Deconstruction allows us to use very handy syntax to directly export the values of an array or object directly to multiple variables, destructuring Arrays

Deconstruction Array

var arr = [1, 2, 3, 4];
var a = arr[0];
var b = arr[1];
var c = arr[2];
var d = arr[3];
Let [A, B, C, d] = [1, 2, 3, 4];

Console.log (a); 1
console.log (b);//2
destructuring Objects

Deconstruction Object

var Luke = {occupation: ' Jedi ', Father: ' Anakin '};
var occupation = Luke.occupation; ' Jedi '
var father = Luke.father;//' Anakin '
Let Luke = {occupation: ' Jedi ', Father: ' Anakin '};
Let {occupation, father} = Luke;

Console.log (occupation); ' Jedi '
Console.log (father);//' Anakin '

(Back to catalog) Modules

Before ES6, the browser-side modular code, we used libraries like browserify,
In node.js , we use require.
In ES6, we can now directly use AMD and COMMONJS these modules. Exporting in Commonjs

Module.exports = 1;
Module.exports = {foo: ' Bar '};
Module.exports = [' foo ', ' Bar '];
Module.exports = function bar () {};
Exporting in ES6

In ES6, there are a variety of ways to set the export of a module, for example, to export a variable, then use the variable name :

Export Let name = ' David ';
Export let age  = 25;

You can also export a list of objects:

function Sumtwo (A, b) {return
    a + b;
}

function Sumthree (A, B, c) {return
    A + B + C;
}

Export {sumtwo, sumthree};

We can also use a simple export keyword to derive a result value:

Export function Sumtwo (A, b) {return
    a + b;
}

Export function Sumthree (A, B, c) {return
    A + B + C;
}

Finally, we can export a default export :

function Sumtwo (A, b) {return
    a + b;
}

function Sumthree (A, B, c) {return
    A + B + C;
}

Let API = {
    sumtwo,
    sumthree
};

Export default API;

Best Practice : Always use the export default method at the end of the module.
It makes the module's exports clearer and saves you the time to read the entire module for export.
More often, in a large number of COMMONJS modules, the common custom is to set an export value or export object.
This rule is most likely to make our code easier to read and to use COMMONJS and ES6 modules in a more convenient joint. Importing in ES6

ES6 provides several ways to import modules. We can introduce a single file:

Import ' underscore ';

It should be noted here that the way the entire file is introduced executes the top-level code within the file .

Like Python, we can also name references:

Import {sumtwo, sumthree} from ' Math/addition ';

We can even rename these modules using as:

Import {
    sumtwo as addtwonumbers,
    sumthree as Sumthreenumbers
} from ' Math/addition ';

In addition, we can introduce all the things (original: Import all the Things) (also known as namespace introduction)

Import * as util from ' math/addition ';

Finally, we can introduce a list from a number of values in a module:

Import * as Additionutil from ' math/addtion ';
const {sumtwo, sumthree} = Additionutil;

Reference the default object like this:

Import API from ' Math/addition ';
Same As:import {default as API} from ' Math/addition ';

We recommend that a module export a value that is as concise as possible, but sometimes it is necessary to name a reference and default reference can be mixed. If a module is exported in this way:

Foos.js
Export {foo as default, Foo1, Foo2};

So we can import the value of this module:

Import foo, {foo1, foo2} from ' Foos ';

We can also import COMMONJS modules, such as react:

Import react from ' react ';
const {Component, proptypes} = react;

More simplified versions:

Import react, {Component, proptypes} from ' react ';

Note : The value being exported is bound (original: bingdings), not a reference.
Therefore, changing the value of a module will affect other code referencing this module, and must avoid such changes.

(Back to catalog) Parameters

In ES5, there are many ways to handle the parameter defaults (default values) of a function, the number of parameters (indefinite arguments), and the name of the parameter (named parameters) .
In ES6, we can use very concise syntax to deal with the above mentioned focus. Default Parameters

function addtwonumbers (x, y) {
    x = x | | 0;
    y = y | | 0;
    return x + y;
}

In ES6, we can simply enable default values for function arguments:

function AddTwoNumbers (x=0, y=0) {return
    x + y;
}
AddTwoNumbers (2, 4); 6
addtwonumbers (2);//2
addtwonumbers ();//0
Rest Parameters

In ES5, we can only do this when the number of parameters is uncertain:

function logarguments () {for
    (var i=0 i < arguments.length; i++) {
        console.log (arguments[i]);
    }

Using the rest operator, we can pass an indeterminate number of argument lists to a function:

function logarguments (... args) {for
    (let Arg of args) {
        console.log (ARG);
    }
}
Named Parameters

Named functions
In ES5, when we are dealing with multiple named parameters , we usually pass in the way of an option object , which is used by jquery.

function Initializecanvas (options) {
    var height = options.height | |
    var width  = options.width  | |
    var linestroke = Options.linestroke | | ' Black ';
}

We can use the new features mentioned above to deconstruct the same functions as above:
We can achieve the same functionality using destructuring as a formal parameter
to a function:

function Initializecanvas (
    {height=600, width=400, linestroke= ' black '}) {
        //...
    }
    Use variables height, width, linestroke

If we need to make this argument optional, just deconstruct the argument to an empty object:

function Initializecanvas (
    {height=600, width=400, linestroke= ' black '} = {}) {
        //...
    }
spread Operator

We can use the expansion operator (spread Operator) to pass the values of a set of arrays as arguments:

Math.max (.....) [-1, 100, 9001,-32]); 9001

(Back to catalog) Classes

Before ES6, when we implemented the functionality of a class, we needed to first create a constructor and then extend the prototype method of the function, like this:

function person (name, age, gender) {
    this.name   = name;
    This.age    = age;
    This.gender = gender;
}

Person.prototype.incrementAge = function () {return
    this.age + = 1;
};

It is necessary to inherit a subclass of a parent class:

function Personal (name, age, gender, occupation, hobby) {
    Person.call (this, name, age, gender);
    this.occupation = occupation;
    This.hobby = hobby;
}

Personal.prototype = Object.create (person.prototype);
Personal.prototype.constructor = Personal;
Personal.prototype.incrementAge = function () {return
    Person.prototype.incrementAge.call (this) =;
};

ES6 provides some syntax sugar to achieve the above function, we can directly create a class:

Class Person {
    constructor (name, age, gender) {
        this.name   = name;
        This.age    = age;
        This.gender = gender;
    }

    Incrementage () {
      this.age + = 1;
    }
}

Inheriting a subclass of a parent class can be as simple as using the Extends keyword:

Class Personal extends Person {
    constructor (name, age, gender, occupation, hobby) {
        super (name, age, gender); 
  
   this.occupation = occupation;
        This.hobby = hobby;
    }

    Incrementage () {
        super.incrementage ();
        This.age +;
        Console.log (this.age);
    }

  

Best Practice : ES6 The new class syntax frees us from arcane implementations and prototyping operations, which is ideal for beginners, and allows us to write cleaner and cleaner code.

(Back to catalog) symbols

The symbols (symbols) existed before the ES6 version, but now we have a common interface to use them directly.
Symbols objects are keys that cannot be changed once they are created (immutable) and can be used as a key in a hash data type. Symbol ()

Calling symbol () or symbol (descriptive text) creates a unique symbolic object that is not accessible in the global.
A Symbol () scenario is where you use a Third-party code base in your own project, and you need to patch code to their objects or namespaces without having to change or upgrade a third party's original code.
For example, if you want to add a Refreshcomponent method to this class of react.component, but you don't know if the method will be added to the next release, you can do this:

Const Refreshcomponent = Symbol ();

React.component.prototype[refreshcomponent] = () => {
    //do something
}
symbol.for (Key)

Using Symbol.for (key) also creates an immutable Symbol object, but differs from the creation method above, which is accessible in the global.
Calling two times symbol.for (key) returns the same Symbol instance.

hint : This is different from Symbol (description).

Symbol (' foo ') = = = Symbol (' foo ')//False
symbol.for (' foo ') = = = (' foo ')//False Symbol.for (' foo ')
= = = Symbol.for (' foo ')//True

A common use scenario for a symbols is the need to use a special symbol.for (key) method to collaborate between code.
This allows you to find symbol members in third party code that contains a known interface in your code. (Translator: This sentence is very difficult to turn ...) Original: This can
achieved by has your code look for a Symbol member on object arguments from third parties that contain some known inter Face. ) For example:

function Reader (obj) {Const Specialread = symbol.for (' Specialread ');
        if (Obj[specialread]) {Const READER = Obj[specialread] (); Do something with reader} 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.