ES6 core content (on)

Reprinted from: https://segmentfault.com/a/1190000004365693

 

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

In other words, ES6 is ES2015.

Although not all browsers are currently compatible with all the features of ES6, more and more programmers have begun to use ES6 in actual projects. So even if you don't plan to use ES6 now, in order to understand other people, you should know some ES6 syntax...

Before we can formally explain ES6 syntax, we must first understand Babel.
Babel

Babel is a widely used ES6 transcoder that can convert ES6 code to ES5 code for execution in existing environments. You can choose the tools you are used to to use Babel. The specific process can be viewed directly on Babel's official website:

 

The most commonly used ES6 features

let, const, class, extends, super, arrow functions, template string, destructuring, default, rest arguments
These are some of the most commonly used syntaxes in ES6. Basically, by learning them, we can travel all over the world without fear! I will use the most simple language and examples to explain them, to ensure that you can understand it at a glance, and you will learn it as soon as you learn it.

let, const

The uses of these two are varsimilar, and they are used to declare variables, but in actual use, they both have their own special uses.
First look at the following example:

var name = 'zach'

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

console.log(name)  //obama

The output of using var both times is obama, because ES5 only has global scope and function scope, and no block-level scope, which brings many unreasonable scenarios. The first scenario is that you are now seeing inner variables overriding outer variables. Instead let, it actually adds block-level scope to JavaScript. Variables declared with it are only letvalid within the code block where the command is located.

let name = 'zach'

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

console.log(name)  //zach

Another varunreasonable scenario is that the loop variable used for counting leaks into a global variable, see the following example:

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

In the above code, the variable i is declared as var and is valid in the global scope. So each time through the loop, the new i value will overwrite the old value, resulting in the final output of the i value of the last round. Using let does 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 to see how closures can solve this problem without ES6.

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

We would have expected to click on different clickBoxes to display different i, but the truth is that no matter which clickBox we click, the output is 5. Let's take a look at how to do it with closures.

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 variables, but declare constants. Once declared, the value of the constant cannot 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 declared with const, the browser will report an error.
Const has a good application scenario, that is, variables declared when we refer to third-party libraries, using const to declare can avoid bugs caused by accidental renaming in the future:

const monent = require('moment')

class, extends, super

These three features cover some of the most annoying parts of ES5: prototypes, constructors, inheritance... Are you still troubled by their complicated syntax? Are you still confused about where the pointer is pointing?

With ES6 we no longer worry!

ES6 provides a writing method that is closer to traditional languages ​​and introduces the concept of Class. The new class writing method makes the writing method of object prototype clearer, more like the syntax of object-oriented programming, and easier to understand.

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

The above code first classdefines a "class". You can see that there is a constructormethod in it, which is the constructor, and the thiskeyword represents the instance object. Simply put, constructorthe methods and properties defined inside are owned by the instance object, while the methods and properties defined constructoroutside are shared by all instance objects.

Inheritance between classes can be achieved through extendskeywords, which is much clearer and more convenient than ES5's implementation of inheritance by modifying the prototype chain. The above defines a Cat class, extendswhich inherits all the properties and methods of the Animal class through keywords.

superkeyword, which refers to the instance of the parent class (ie the this object of the parent class). The subclass must constructorcall the method in the supermethod, otherwise an error will be reported when creating an instance. This is because the subclass does not have its own thisobject, but inherits the thisobject of the parent class and then processes it. If you don't call superthe method, the subclass doesn't get the thisobject.

The essence of the inheritance mechanism of ES6 is to first create the instance object this of the parent class (so the super method must be called first), and then use the constructor of the subclass to modify this.

PS If you write react, you will find that the above three things appear a lot in the latest version of React. Each component created is an inherited React.Componentclass. See the react documentation for details

arrow function

This is probably the most commonly used new feature of ES6. Using it to write functions is much more concise and clearer than the original way of writing:

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

It's so simple, right...
If the equations are more complicated, you need to {}wrap the code with:

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

In addition to looking more concise, arrow function also has a super invincible function!
Objects in the JavaScript language have long thisbeen a headache, and you must be very careful when using this in object methods. 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

Running the above code will report an error, because setTimeoutthe in thisrefers to the global object. So in order to make it work correctly, there are two traditional solutions:

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

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

    2. The second method is to use bind(this), namely

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

    But now that we have arrow functions, we don't need to bother:

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 arrow functions, the this object in the function body is the object where it is defined, not the object where it is used.
It's not because there is a mechanism for binding this inside the arrow function. The actual reason is that the arrow function does not have its own this at all. Its this is inherited from the outside, so the inner this is the this of the outer code block.

template string

This thing is also very useful. When we want to insert large pieces of html content into the document, the traditional writing method is very troublesome, so we usually refer to some template tool libraries, 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 '+' signs to connect text and variables, and using ES6's new feature template string ``, we can write it directly like this:

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

Use backticks (\) 来标识起始,用${}` to quote variables, and all whitespace and indentation will be preserved in the output, isn't it cool? !

React Router also uses ES6 syntax since version 1.0.3, such as this example:

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

React Router

destructuring

ES6 allows to extract values ​​from arrays and objects and assign values ​​to variables according to a certain pattern, which is called Destructuring.

See the example below:

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

In ES6, you can write it like this:

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

The reverse can be written like this:

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

default, rest

default is very simple, it means the default value. You can look at the following example. When calling animal()the method, you forget to pass parameters. The traditional method is to add this sentence type = type || 'cat' to specify the default value.

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

If we use ES6, we have written this directly:

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

The last rest syntax is also very simple, just look at the example:

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

And if we don't use ES6, we have to use ES5 arguments.

Summarize

The above are some of the most commonly used grammars of ES6. It can be said that these 20% grammars account for 80% of the daily use of ES6...

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326410783&siteId=291194637