30 minutes to master the ES6 / ES2015 core (on)

ECMAScript 6 (hereinafter referred to as ES6) is the next generation standard JavaScript language. Because the current version of the ES6 was released in 2015, also known as ECMAScript 2015.

In other words, ES6 is the ES2015.

Although not all browsers are compatible ES6 all the features, but more and more programmers have started using ES6 in which actual project. So even if you are not going to use ES6, but in order to understand other people's grammar point you should also know ES6 of the ...

Before we explain ES6 grammar, we must first understand Babel.
Babel

Babel ES6 transcoder is a widely used, can be converted to the code ES6 ES5 code to execute in a conventional environment. We can choose to use their own custom tools using Babel, the specific process can be viewed directly in Babel's official website:
https://babeljs.io/docs/setup/

The most common characteristic ES6

let, const, class, extends, super, arrow functions, template string, destructuring, default, rest arguments
These are the most commonly used several ES6 grammar, basically learn them, we can over the world are not afraid of you! I will use the most easy to understand language and examples to explain them, to ensure a look to understand, learn.

let, const

Both use and varsimilar, are used to declare variables, but in practical application They have their own special purposes.
First look at the following example:

var name = 'zach'

while (true) {
    var name = 'obama' console.log(name) //obama break } console.log(name) //obama

Use var two outputs are obama, since ES5 only global scope and function scope, not block-level scope, which bring a lot of irrational scenes. The first scenario is that you're seeing the inner cover variable outer variable. And letit actually added a JavaScript block-level scope. Variables declared with it, only letvalid within a block command is located.

let name = 'zach'

while (true) {
    let name = 'obama' console.log(name) //obama break } console.log(name) //zach

Another varbrought reasonable scenario is the loop variable for counting leakage global variables, see the following example:

var a = [];
for (var i = 0; i < 10; i++) { a[i] = function () { console.log(i); }; } a[6](); // 10

The above code, the variable i is declared var, valid globally. So every time cycle, the new value will overwrite the old value of i, leading to the final output is the value of the final round of the i's. The use let it not have this problem.

var a = [];
for (let i = 0; i < 10; i++) { a[i] = function () { console.log(i); }; } a[6](); // 6 

Let's look at a more common example, if you do not understand at ES6, but with closures how to solve this problem.

var clickBoxs = document.querySelectorAll('.clickBox')
for (var i = 0; i < clickBoxs.length; i++){ clickBoxs[i].onclick = function(){ console.log(i) } }

We would have liked is to click on different clickBox, show different i, but the fact is that no matter what we click clickBox, output is 5. Here we look at how to fix it with closure.

function iteratorFactory(i){
    var onclick = function(e){ console.log(i) } return onclick; } var clickBoxs = document.querySelectorAll('.clickBox') for (var i = 0; i < clickBoxs.length; i++){ clickBoxs[i].onclick = iteratorFactory(i) } 

constAlso used to declare a variable, but the statement is a constant. Once declared, the value of the constant can not be changed.

const PI = Math.PI

PI = 23 //Module build failed: SyntaxError: /es6/app.js: "PI" is read-only

When we try to change the constant with the const statement, the browser will give an error.
const there is a good scenario is that when we refer to when you declare a variable third-party libraries, and use const to declare the future to avoid accidentally rename and cause bug:

const monent = require('moment')

class, extends, super

These three characteristics relate to the ES5 in several parts of the most troubling: the prototype constructors, inheritance ... you are still the intricacies of grammar as they worry about it? Are you still pointer in the end point where very tangled it?

With ES6 we no longer worry!

ES6 provided closer to the traditional language of the writing, we introduce Class (Class) concept. The new wording allows writing class object's prototype clearer, like object-oriented programming syntax, and more user-friendly.

class Animal {
    constructor(){
        this.type = 'animal' } says(say){ console.log(this.type + ' says ' + say) } } let animal = new Animal() animal.says('hello') //animal says hello class Cat extends Animal { constructor(){ super() this.type = 'cat' } } let cat = new Cat() cat.says('hello') //cat says hello

First, using the above code classdefines a "class", there can be seen a constructormethod, which is the constructor, the thiskeyword represents the object instance. Briefly, constructorwithin the definition of the methods and properties of the object's own instance, the constructorouter definition of the methods and properties are all instances of objects that can be shared.

By between Class can extendsachieve a keyword inheritance, inheritance by modifying the prototype chain than ES5, to clear and a lot easier. The above definition of a Cat class, by extendskeyword, inherits all the attributes and methods Animal class.

superKeyword that refers to an instance (i.e. this object's parent class) on behalf of the parent class. Subclass must constructorcall the method supermethod, otherwise it will error when creating a new instance. This is because the subclass does not own thisthe object, but inherit the parent class thisobject, then its processing. If you do not call the supermethod, the subclass would not thisobject.

ES6 inheritance mechanism, the essence is to create an object instance of this parent class (you must first call the super method), then use the constructor subclass modify this.

PS If you write react, it would have found that more than three things appear a lot in the latest version of React. Each component is to create a succession React.Componentof class. See react document

arrow function

This is probably the most commonly used ES6 a new feature, and use it to write function to be simpler than the original wording of many clear:

function(i){ return i + 1; } //ES5 (i) => i + 1 //ES6

Simple is simply outrageous, right ...
If the equation is more complex, you need to use {}to wrap the code:

function(x, y) { 
    x++;
    y--;
    return x + y; } (x, y) => {x++; y--; return x+y}

In addition to look more concise, arrow function also has a super-invincible function!
For a long time, JavaScript language of thisobjects has been a vexing problem, the use of this method in the object must be very careful. E.g:

class Animal {
    constructor(){
        this.type = 'animal' } says(say){ setTimeout(function(){ console.log(this.type + ' says ' + say) }, 1000) } } var animal = new Animal() animal.says('hi') //undefined says hi

Run the above code will complain, because setTimeoutthe thispoint is the global object. Therefore, in order to allow it to run correctly, there are two traditional solutions:

  1. The first is to pass this self, then to refer to this self

       says(say){
           var self = this;
           setTimeout(function(){ console.log(self.type + ' says ' + say) }, 1000)

    2. The second method is used bind(this), that is,

       says(say){
           setTimeout(function(){
               console.log(this.type + ' says ' + say) }.bind(this), 1000)

    But now we have the arrow function, you do not need too much trouble:

class Animal {
    constructor(){
        this.type = 'animal' } says(say){ setTimeout( () => { console.log(this.type + ' says ' + say) }, 1000) } } var animal = new Animal() animal.says('hi') //animal says hi 

When we use the arrow function, the function of this body of objects, where the object is to define when, while you were on when not use.
Not because there is an internal mechanism to bind this function arrow, the actual reason is a function of the arrow did not own this, it is inherited outside of this, so this is the inside of this outer code block.

template string

This thing is very useful when we want to insert html content to a large section of the document, the traditional wording is very troublesome, so before we usually quote some template tool library, such as mustache and so on.

You can look at the following piece of code:

$("#result").append(
  "There are <b>" + basket.count + "</b> " +
  "items in your basket, " +
  "<em>" + basket.onSale + "</em> are on sale!" ); 

We use a bunch of '+' sign to connect the variable text, and use the new features of template string `` ES6, so we can write directly to:

$("#result").append(`
  There are <b>${basket.count}</b> items
   in your basket, <em>${basket.onSale}</em>
  are on sale!
`);

With anti-quotation marks (\) $ 来标识起始,用{} `to refer to the variables, and all spaces and indentation are preserved in the output being, is not very cool? !

React Router from version 1.0.3 to start ES6 also use the syntax, such as this example:

<Link to={`/taco/${taco.name}`}>{taco.name}</Link> 

React Router

destructuring

ES6 allowed according to a certain pattern, and the object is extracted from an array of values, variable assignment, which is referred to deconstructed (Destructuring).

See the examples below:

let cat = 'ken'
let dog = 'lili'
let zoo = {cat: cat, dog: dog} console.log(zoo) //Object {cat: "ken", dog: "lili"}

It can be completely written like this with ES6:

let cat = 'ken'
let dog = 'lili'
let zoo = {cat, dog} console.log(zoo) //Object {cat: "ken", dog: "lili"}

In turn, could write:

let dog = {type: 'animal', many: 2}
let { type, many} = dog console.log(type, many) //animal 2 

default, rest

default is very simple, which means the default. We can look at the example below, calling animal()forgot pass parameter method, the traditional approach is to add this one type = type || 'cat' to specify a default value.

function animal(type){
    type = type || 'cat' console.log(type) } animal()

If we only use ES6 direct write:

function animal(type = 'cat'){
    console.log(type) } animal() 

The last rest grammar is also very simple, direct look at an example:

function animals(...types){ console.log(types) } animals('cat', 'dog', 'fish') //["cat", "dog", "fish"]

And if that is not ES6, we then have to use the ES5 arguments.

to sum up

These are some of the most commonly used ES6 grammar, we can say that 20% of grammar, accounted for 80 percent of daily use ES6 in ...

 

30 minutes to master the ES6 / ES2015 core (lower)

Guess you like

Origin www.cnblogs.com/ysx215/p/11390376.html