New Features of es6 & ecmascript2015

Source: Internet
Author: User

 


Ecmascript 6 (es6) is the next-generation standard for JavaScript. Because the current version of es6 was released in 2015, it is also called ecmascript 2015.

That is to say, es6 is es2015.

Although not all browsers are compatible with all es6 features, more and more programmers are using es6 in actual projects. So even if you don't want to use es6 now, you should understand es6 syntax to understand others...

Before we officially explain es6 syntax, we must first understand Babel.
Babel

Babel is a widely used es6 Transcoder that can convert es6 code into es5 code for execution in an existing environment. You can use the tools you are used to use Babel. You can view the specific process on the Babel Official Website:


Https://babeljs.io/docs/setup/the most common es6feature

let, const, class, extends, super, arrow functions, template string, destructuring, default, rest arguments
These are the most commonly used syntaxes of es6. Basically, we can go all over the world without fear! I will explain them in the most easy-to-understand languages and examples, so that they can be understood at a glance and learned at a glance.

Let, const

The purposes of these two methods are as follows:varSimilarly, they are used to declare variables, but they both have their own special purposes in actual use.
First, let's look at the following example:

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

 

UsevarBoth outputs are Obama, because es5 only has global and function scopes and does not have block-level scopes, which leads to many unreasonable scenarios. The first scenario is that the inner variable you see overwrites the outer variable. WhileletIn fact, the block-level scope is added to JavaScript. The variables declared with it areletThe code block in which the command resides is valid.

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

 

AnothervarThe unreasonable scenario is that the cyclic variables used to count are leaked as global variables. See the following example:

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

 

In the code above, variable I is declared by VAR and is valid globally. Therefore, in each loop, the new I value will overwrite the old value, resulting in the final output of the last round of I value. Using let will not cause 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 learn how to solve this 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) } }

 

We originally wanted to click different clickboxes to display different I, but the fact is that no matter which clickbox we click, the output is 5. Next, let's take a look at how to fix 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) }

 

constIt is also used to declare variables, but declared as constants. Once declared, the constant value cannot be changed.

const PI = Math.PIPI = 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, when we reference the variables declared when a third-party library, using const to declare can avoid bugs caused by accidental renaming in the future:

const monent = require(‘moment‘)

 

Class, extends, super

These three features involve the most troublesome parts of es5: Prototype, constructor, inheritance... Are you still worried about their complicated and difficult syntax? Are you still struggling with where the Pointer Points?

With es6, we are no longer worried!

Es6 provides a method that is closer to traditional languages and introduces the concept of class. The new class writing method makes the object prototype writing clearer, more like the object-oriented programming syntax, and more easy 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 usesclassDefines a "class". You can see that there isconstructorMethod, which is the constructor method, andthisKeyword indicates the instance object. Simply put,constructorThe methods and properties defined inconstructorThe methods and attributes defined by the external definition can be shared by all the strength objects.

You can useextendsKeyword implementation inheritance is much clearer and more convenient than es5's implementation of inheritance by modifying the prototype chain. The cat class is defined above.extendsKeyword that inherits all attributes and methods of the animal class.

superKeyword, which refers to the instance of the parent class (that is, the this object of the parent class ). Subclass must be inconstructorMethod callsuperOtherwise, an error is returned when you create an instance. This is because the subclass does not have its ownthisObject, but inheritsthisObject, and then process it. If you do not callsuperMethod, the subclass will not be availablethisObject.

The Inheritance Mechanism of es6 is to first create the Instance Object of the parent class this (so the super method must be called first), and then modify this with the constructor of the subclass.

P.s if you write react, you will find that the above three items appear in the latest version of react. Each component created is an inheritanceReact.Component. For details, see react documentation.

Arrow Function

This is probably the most common new feature of es6. using it to write functions is much simpler and clearer than the original writing method:

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

 

It's simple, right...
If the equation is complex, use{}Pack the Code:

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

 

In addition to simplicity, arrow function also has a Super invincible feature!
For a long timethisObjects have always been a headache and you must be very careful when 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

 

If you run the above Code, an error is reported. This is becausesetTimeoutInthisIt points to a global object. Therefore, to make it run correctly, there are two traditional solutions:

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 usebind(this), That is

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

 

 

But now we have the arrow function, so we don't need to worry about it:

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, this object in the function body is the object in the definition, not the object in use.
It is not because the arrow function has a mechanism to bind this internally. The actual reason is that the arrow function does not have its own this, and its this inherits from the outside, so the internal this is the this of the outer code block.

Template string

This is also very useful. When we want to insert large sections of HTML content into the document, the traditional writing method is very troublesome. Therefore, we usually reference some template tool libraries, such as mustache.

You can read the following code first:

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

 

We need to use a bunch of '+' numbers to connect text and variables. After using the new es6 template string, we can directly write it like this:

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

 

Use quotation marks(`)To identify the start point.${}To reference variables, and all spaces and indentation will be kept in the output. Isn't it so nice ?!

React router also uses es6 syntax from version 1.0.3. For example:
<Link to={`/taco/${taco.name}`}>{taco.name}</Link>
React Router

Destructuring

Es6 allows you to extract values from arrays and objects in a certain mode and assign values to variables. This is called destructuring ).

See the following example:

Let cat = 'ken' Let dog = 'lili' let zoo = {Cat: cat, dog: Dog} console. log (zoo) // object {Cat: "Ken", dog: "Lili"} 123 with es6 can be written as follows: let cat = 'ken' Let dog = 'lili' let zoo = {cat, dog} console. log (zoo) // object {Cat: "Ken", dog: "Lili "}

 

This can be written in turn:

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

 

Default, rest

Default is simple, which means the default value. You can refer to the following example to callanimal()You forget to pass parameters when using the method. 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 es6 is used, we can write it like this:

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

 

The last rest syntax is also very simple. Let's look at the example:

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

 

 

If es6 is not used, we need to use es5arguments.

New Features of es6 & ecmascript2015

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.