ECMASCRIPT6 Quick Start (novice must SEE)

Source: Internet
Author: User
Tags inheritance

With the support of Google and Firfox and node6.0 for ES6, the finalization of the ES6 syntax has given it more and more attention, especially react projects are written mostly in ES6. It's time to change from ES5 to ES6.
<!--more--> , related background introduction

The syntax JavaScript that most of us use today is ecmscript5, and it's es5. This version has been for many years, and is perfectly supported by the major browsers. So a lot of learning JS friends can always be unclear es5 and javscript relationship. JavaScript is a programming language, then it has a version, ES5 or ES6 is its version number. The latest version of ES7 has been in the process of tight gong, its latest syntax will let us write code update of the flowing clouds. Second, Babel a ES6 parser

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

Babel is a widely used ES6 transcoding that converts ES6 code to ES5 code to perform in an existing environment. People can choose their own custom tools to use Babel, my favorite building tool is Webpack. The specific process can be directly in Babel official website view: Three, grammar

The most commonly used ES6 characteristics

Let, const, class, extends, super, arrow functions, Template String, destructuring, default, rest arguments
These are the ES6 most commonly used grammar, basically learn them, we can travel around the world are not afraid of it. I will use the most understandable language and examples to explain them, to ensure that a look at the understanding, a learning will. 1. Let, const

These two uses are similar to Var and are used to declare variables, but in practice 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 use of Var two output is Obama, because ES5 only global scope and function scope, there is no block level scope, this brings a lot of unreasonable scenarios. The first scenario is that the inner variables you see now cover the outer variables. Let, in effect, adds a block-level scope to JavaScript. Use the variable it declares to be valid only within the block of code where the Let command is located.

Another unreasonable scenario that Var brings is that the loop variable used to count is leaked as a global variable, see the following example:

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

In the code above, the variable i is declared by VAR and is valid globally. So in each cycle, the new I value overwrites the old value, resulting in the final output of the value of I of the last round. And using let does not appear this problem.

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

Let's look at a more common example of how to solve the problem with closures without ES6.

var clickboxs = Document.queryselectorall ('. Clickbox ') for
(var i = 0; i < clickboxs.length; i++) {
    clickboxs[i ].onclick = function () {
        console.log (i)
    }
}

What we would have wanted was to click on different clickbox to show the different I, but the fact is that no matter which clickbox we click, the output is 5. Let's look at how to handle it with a 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)
}

A const is also used to declare a variable, but a constant is declared. Once declared, the value of a constant cannot be changed.

Const PI = math.pi

pi =//module build failed:syntaxerror:/es6/app.js: ' PI ' is read-only

When we try to change constants declared with const, the browser complains. The const has a good scenario, when we refer to a variable declared by a third party library, and a const declaration can avoid future accidentally renaming causing the bug to occur:

Const Monent = require (' moment ')
2. Class, extends, Super

These three features cover some of the most vexing parts of ES5: Prototypes, constructors, inheritance ... Are you still bothered by their complicated grammar? Are you still obsessed with where the pointer is pointing?

With ES6, we are no longer troubled.

ES6 provides a closer approach to the traditional language, introducing the concept of Class (class). The new class notation makes the object prototype more explicit, more like object-oriented programming syntax, and more understandable.

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 code above first defines a "class" with class, and you can see that there is a constructor method, which is the construction method, and the This keyword represents the instance object. Simply put, the methods and properties defined within constructor are the instance objects themselves, while the methods and properties defined outside constructor are shared by all instance objects.

Class can be inherited through the extends keyword, which is much clearer and more convenient than ES5 's inheritance by modifying the prototype chain. The above defines a cat class that inherits all the properties and methods of the animal class through the extends keyword.

Super keyword, which refers to an instance of the parent class (that is, the this object of the parent class). Subclasses must call the Super method in the constructor method or the new instance will have an error. This is because the subclass does not have its own this object, but instead inherits the this object of the parent class and then processes it. If you do not call the Super method, the subclass will not get the This object.

The ES6 inheritance mechanism is essentially creating the instance object of the parent class this (so the super method must be called first) and then modifying this with the constructor of the subclass.

P.S If you write react, you will find that the above three items appear a lot in the latest version of react. Each component that you create is a class that inherits React.component. See React document 3. Arrow function

This is probably one of the most common features of ES6, and using it to write a function is much simpler and clearer than the original:

function (i) {return i + 1;}//es5
(i) => i + 1//es6

It's simply outrageous, right?
If the equation is more complex, you need to wrap the code with {}:

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

Apart from looking more concise, arrow function has a super invincible function.
The This object of the JavaScript language has long been a headache, and you must be very careful about using this in object methods. For example:

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 cause an error, because this is the global object that is pointed to in the settimeout. So in order for it to work correctly, there are two traditional ways to solve the problem:

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)

The second method is to use BIND (this), which is

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

But now that we have the arrow function, there's no 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 the arrow function, the This object in the body of the function is the object of the definition, not the object in which it is used. Not because the arrow function has a mechanism for binding this, the actual reason is that the arrow function does not have its own this, its this is inherited outside, so the internal this is the outer code block this. 4. Template String

This thing is also very useful, when we want to insert a large section of HTML content into the document, the traditional wording is very cumbersome, so we usually refer to some template ToolPak, such as mustache and so on.

You can first look at the following code:

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.