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‘zach‘while (true) { var‘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‘zach‘while (true) { let‘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 (var010; 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 (let010; 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.
vardocument.querySelectorAll(‘.clickBox‘)for (var0; i < clickBoxs.length; i++){ 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){ varfunction(e){ console.log(i) } return onclick;}vardocument.querySelectorAll(‘.clickBox‘)for (var0; 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.
const23failedSyntaxError: /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:
constrequire(‘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.
class Animal {Constructor () { This. Type =' Animal '} says (say) {Console. log ( This. Type +' says '+ Say)}} LetAnimal =NewAnimal () Animal.says (' Hello ')//Animal says hello class Cat extends Animal {Constructor () {Super() This. Type =' Cat '}} LetCat =NewCat () Cat.says (' Hello ')//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)return1//ES51//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--; returnreturn 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‘animal‘ } says(say){ setTimeout(function(){ console.log(this‘ says ‘ + say) 1000) varnew 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){ varthis; setTimeout(function(){ console‘ says ‘ + say) 1000)
2. The second method is used bind(this)
, i.e.
says(say){ setTimeout(function(){ console.log(this‘ says ‘ + say) }.bind(this1000)
But now that we have the arrow function, we don't need to be so troublesome:
class Animal { constructor(){ this‘animal‘ } says(say){ () => { console.log(this‘ says ‘ + say) 1000) varnew 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>""</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 <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‘ken‘let‘lili‘let zoo = {catdog: dog}console.log(zoo) //Object {cat"ken"dog"lili"}
Using ES6 can be written like this:
let‘ken‘let‘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‘2}lettype, many} = dogconsole.log(type, many) 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){ typetype‘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
Above is ES6 most commonly used some grammar, can say this 20% grammar, in ES6 's daily use occupies 80% ...
10 minutes to add, okay? :)
30 minutes to master ES6 core content (next)
30 minutes to master ES6 core content