ECMAScript 6 (hereinafter referred to as ES6) is the next generation of JavaScript language standards. Since the current version of ES6 was released in 2015, it is also called ECMAScript 2015.
In other words, ES6 is ES2015.
While not all browsers are compatible with ES6 all features at this time, more and more programmers are already using ES6 in actual projects. So even if you don't plan to use ES6 now, you should know a little bit about ES6 's grammar in order to understand Others.
Before we formally explain the ES6 grammar, we have to understand the babel.
Babel
Babel is a widely used ES6 transcoding device that converts ES6 code into ES5 code, which can be executed in an existing Environment. You can choose your own custom tools to use babel, the specific process can be directly on the Babel official website to View:
The most commonly used ES6 features
let, const, class, extends, super, arrow functions, template string, destructuring, default, rest arguments
These are the most commonly used ES6 grammar, basically learn them, we can go all over the world is not afraid of! I will use the most understandable language and examples to explain them, to ensure that a look at the understanding, a learning Will.
let, Const
The use of these two var
is similar, is used to declare variables, but in practical use, they have their own special purpose.
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 var
of two output is obama, because ES5 only global scope and function scope, There is no block-level scope, which brings a lot of unreasonable scenes. The first scenario is that the inner variables you see now cover the outer variables. Instead let
, a block-level scope is actually added to Javascript. Use the variable it declares to be valid only let
within the code block where the command resides.
let name = ‘zach‘while (true) { let name = ‘obama‘ console.log(name) //obama break}console.log(name) //zach
Another unreasonable var
scenario is that the loop variable used to count is leaked as a global variable, as shown in 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 Var and is valid at the global Scope. So each cycle, the new I value will overwrite the old value, resulting in the final output of the last round of the I Value. With let, This problem does not occur.
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 of 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) }}
What we would have liked 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 take a look at how to fix 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)}
const
It is also used to declare a variable, but a constant is Declared. Once declared, the value of the constant 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 constants declared with const, the browser will Error. Const has a good application scenario, that is, when we refer to a Third-party library declaration of variables, with a const declaration can avoid the future accidentally renamed to cause a bug:
const monent = require(‘moment‘)
class, extends, Super
These three features cover some of the most vexing parts of ES5: prototypes, constructors, inheritance ... Are you still worried about their complicated grammar? Are you still struggling with where the pointer is pointing?
With the ES6 we are no longer troubled!
ES6 provides a more similar approach to traditional languages, introducing the concept of class. The new class notation makes the object prototype more legible, more like object-oriented programming syntax, and more Understandable.
ClassAnimal {constructor () { this.type = ' animal '} says (say) { Console.log (this.type + ' says ' + Say)}}let animal = new animal () animal.says ( ' Hello ') Span class= "hljs-regexp" >//animal says Helloclass cat extends animal {constructor () {super () this.type = ' cat '}}//cat says hello
The above code first class
defines a "class", you can see that there is a constructor
method, which is the construction method, and the this
keyword represents the instance Object. In short, the constructor
methods and properties defined inside are the instance objects themselves, while the constructor
methods and properties defined outside are the one that all instance objects can Share.
Class can be inherited through the extends
keyword, which is more clear and convenient than ES5 through the modification of the prototype chain to achieve INHERITANCE. The above defines a cat class that extends
inherits all the properties and methods of the animal class through the Keyword.
super
keyword, which refers to an instance of the parent class (that is, The This object of the parent class). The subclass must call the method in the constructor
method super
, or the new instance will have an Error. This is because the subclass does not have its own this
object, but instead inherits the object of the parent class and this
then processes it. If you do not call super
a method, the subclass will not get the this
object.
The inheritance mechanism of ES6 is essentially the creation of the instance object of the parent class (so The Super method must be called first), and then this is modified with the constructor of the Subclass.
P.S If you write a react, you will find that the above three things appear in the latest version of React. Each component that is created is an inherited React.Component
class. See React documentation
Arrow function
This is probably the most common use of ES6 a new feature, using it to write function than the original wording to be concise and clear a lot:
function(i){ return i + 1; } //ES5(i) => i + 1 //ES6
It's simply outrageous, isn't it?
If the equation is more complex, you need to {}
wrap the code together:
function(x, y) { x++; y--; return x + y;}(x, y) => {x++; y--; return x+y}
In addition to looking more concise, arrow function has a super invincible function!
For a long time, the object of JavaScript language this
has been a headache, and using this in object methods must be very careful. 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 result in an error, because the setTimeout
this
pointer is to a global object. So in order for it to 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)}, +)
2. The second method is to use bind (this)
. That is
says (say) {setTimeout (function () {console.log (t His.type + ' says ' + say)}.bind (this), 1000)
But now that we have an arrow function, we don't need that 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 This object in the body of the function is the object that is defined, not the object in which it is Used. It is not because the arrow function has the mechanism of 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 of This.
Template string
This thing is also very useful, when we want to insert large pieces of HTML content into the document, the traditional writing is very troublesome, so we usually refer to some template tool library, such as mustache and so On.
You can first look at the following code:
$("#result").append( "There are <b>" + basket.count + "</b> " + "items in your basket, " + "<em>" + basket.onSale + "</em> are on sale!");
We're going to use a bunch of ' + ' to connect text and variables, and using ES6 's new feature template string ', We can write this directly:
$("#result").append(` <b>${basket.count}</b> items in your basket, <em>${basket.onSale}</em> are on sale!`);
(\
来标识起始,用
${} ' To reference the variable, and all the spaces and indents will be preserved in the output, is not very cool?!
React router also used ES6 syntax starting from version 1th 0.3, such as this 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 pattern, assigning values to variables, which is called deconstruction (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"}
Using ES6 can be written like this:
let cat = ‘ken‘let dog = ‘lili‘let zoo = {cat, dog}console.log(zoo) //Object {cat: "ken", dog: "lili"}
In turn, it can be written like this:
let dog = {type: ‘animal‘, many: 2}let { type, many} = dogconsole.log(type, many) //animal 2
default, Rest
Default is simple, meaning that it is the Defaults. You can see the following example, the method is called to animal()
forget to pass parameters, the traditional practice 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 just write this:
function animal(type = ‘cat‘){ console.log(type)}animal()
The last rest syntax is simple, just look at an example:
function animals(...types){ console.log(types)}animals(‘cat‘, ‘dog‘, ‘fish‘) //["cat", "dog", "fish"]
And if we don't have to ES6, we'll have to use ES5 arguments
.
Summarize
This article reproduced, thanks to the original Author's meticulous finishing.
The ES6 of JavaScript