Most commonly used ES6 features

let, const, class, extends, super, arrow functions, template string, destructuring, default, Rest arguments These are some of the most common ES6 grammars, and you can get around to them! I will use the most easy to understand language and examples to explain them, to ensure that you can understand, learn.

let, const

These two functions are similar to var in that they are used to declare variables, but in practice they have their own special uses. Let’s start with the following example:

var name = 'zach'

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

console.log(name)  //obama
Copy the code

The output is Obama both times when var is used, because ES5 has only global and function scopes, not block-level scopes, which leads to a lot of irrational scenarios. The first scenario is where you see the inner variables overwriting the outer variables. Let actually adds block-level scope to JavaScript. The variables declared with it are valid only within the code block in which the let command resides.

let name = 'zach'

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

console.log(name)  //zach
Copy the code

Another scenario where var makes sense is when a loop variable used to count is exposed as a global variable, as in the following example:

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

In the code above, the variable I is declared by var and is globally valid. So each time, the new value of I overwrites the old value, resulting in the output of the last value of I. This problem does not occur with let.

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

Let’s take a look at a more common example of how to solve this problem with closures instead of ES6.

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

We were hoping to click on different clickboxes and display different I’s, but the truth is that no matter which clickBox we click on, the output is always 5. Now let’s see how we can do that 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)
}
Copy the code

Const is also used to declare variables, but only constants. Once declared, the value of a constant cannot be changed.

const PI = Math.PI

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

The browser gets an error when we try to change a constant declared as const. A good use of const is when we declare a variable from a third-party library to avoid accidental renaming bugs in the future:

const monent = require('moment')
Copy the code

class, extends, super

These three features address some of the most frustrating parts of ES5: stereotypes, constructors, inheritance… Are you still bothered by their complicated syntax? Are you still struggling with where the pointer is pointing?

With ES6 we don’t worry anymore!

ES6 provides a more traditional language approach, introducing the concept of Class. The new class writing method makes writing object prototypes clearer, more like object-oriented programming syntax, 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 helloCopy the code

The above code first defines a “class” using class. You can see that it has a constructor method, which is the constructor, and the this keyword represents the instance object. Simply put, methods and properties defined within Constructor are the instance object’s own, whereas methods and properties defined outside constructor are shared by all power objects.

Classes can be inherited using the extends keyword, which is much cleaner and more convenient than ES5’s modified prototype chain. This defines a Cat class that extends all properties and methods from the Animal class.

The super keyword, which refers to instances of the parent class (that is, the this object of the parent class). Subclasses must call the super method from the constructor method or they will get an error when creating a new instance. This is because the subclass does not have its own This object, but inherits the parent’s This object and then processes it. If you don’t call super, your subclasses don’t get this.

The inheritance mechanism in ES6 essentially creates an instance object of the parent class, this (so the super method must be called first), and then modifs this with the constructor of the subclass.

If you write React, you’ll see a lot of these three things in the latest version of React. Each component created is a class that inherits react.component. See the React documentation

arrow function

This is probably one of the most commonly used new features in ES6, and it is much cleaner than the original way of writing function:

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

It’s ridiculously simple, isn’t it… If the equation is more complex, you need to wrap the code around {} :

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

In addition to looking simpler, arrow Function has another awesome feature! The JavaScript language’s This object has long been a headache, and using this in object methods must be done with great care. Such as:

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
Copy the code

Running the above code returns an error because this in setTimeout points to a global object. So in order for it to work correctly, there are two traditional solutions:

  1. The first is to pass this to self and refer to this with self

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

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

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

    But now that we have the arrow function, 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
Copy the code

When we use the arrow function, the this object inside the function is the object we defined, not the object we used. This is not because the arrow function has a mechanism inside to bind this, but because the arrow function doesn’t have its own this at all. Its this inherits from the outside, so the inner this is the this of the outer code block.

template string

It’s also very useful because when you’re inserting large chunks of HTML into a document, the traditional way of writing it is very cumbersome, so in the past we used to refer to a template library like Mustache.

You can take a look at the following code:

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

We use a bunch of ‘+’ signs to concatenate text and variables, but with the new ES6 feature template string, we can write it like this:

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

Wouldn’t it be nice to start with backquotes (‘), reference variables with ${}, and keep all whitespace and indentation in the output? !

The React Router also uses ES6 syntax since version 1.0.3, as in this example: {taco.name} React Router

destructuring

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

Look at the following example:

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

With ES6, you could write something like this:

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

The reverse can be written:

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

default, rest

Default is simply the default value. You can see the examples below, call animal () method is forgot to pass parameters, the traditional approach is combined with the sentence type = type | | ‘cat’ to specify a default value.

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

If we use ES6 we just write it like this:

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

The last rest syntax is simple enough to look at directly:

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

If we don’t use ES6, we should use ARGUMENTS for ES5.

conclusion

These are some of the most commonly used ES6 grammars. It can be said that these 20% grammars make up 80% of the daily usage of ES6…

www.jianshu.com/p/ebfeb687e…