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
Above is ES6 most commonly used some grammar, can say this 20% grammar, in ES6 's daily use occupies 80% ...
Most commonly used ES6 characteristics (RPM)