An overview of the new features of ES6

  • 2021-01-25 07:00:36
  • OfStack

Nick Justice is part of the GitHub developer program. Long before the ES6 standard was published, he used ES6 features in his projects with translators like ES5en and the latest versions of browsers. He believes that the new features of ES6 will dramatically change the way JavaScript is written.

ES6 (ECMAScript 6) is the standard for the upcoming version of the JavaScript language, codenamed harmony(Harmony, obviously not keeping up with our country, we are already in the Chinese dream version). The formulation of the last standard or 2009 ES5. Currently, the standardization of ES6 is in progress, and the final version is expected to be released in December 2014. But most of the standards are in place, and browser support for ES6 is in the works.

Although the development of technology is too fast, but we do not stop the pace of learning, will not be eliminated by the new technology, let's 1 up to learn the new features of es6.

Arrow operator

If you know C# or Java, you know the lambda expression, the new arrow operator = in ES6 > They have the same idea. It simplifies the writing of functions. The left side of the operator is the input parameters, while the right side is the operation performed and the return value Inputs= > outputs.

We know that callbacks are a common occurrence in JS, and common callbacks are in the form of anonymous functions, so it is tedious to write one function at a time. It is easy to write callbacks when the arrow operator is introduced. Take a look at the following example:


var array = [1,2,3];
//  The traditional way of writing 
array.forEach(function(v) {
console.log(v);
});
// ES6 writing 
array.forEach(v => console.log(v)); 

The support of the classes

ES44en6 has added support for classes and introduced the ES45en off key (ES46en was reserved in ES47en for the sake of possible use in a later version, but it's finally coming in handy). JS itself is object-oriented, and the classes provided in ES6 are really just wrappers for JS prototype patterns. Now that native class support is provided, object creation, inheritance, and the concepts of parent method calls, instantiation, static methods, and constructors are much more visual.

The following code shows the use of the class in ES6:


//  The definition of a class 
class Animal {
// ES6 A new type of constructor 
constructor(name) {
this.name = name;
}
//  Instance methods 
sayName() {
console.log('My name is ' + this.name);
}
}
//  Class inheritance 
class Programmer extends Animal {
constructor(name) {
//  Initialize directly by calling the parent class constructor 
super(name);
}
program() {
console.log("I'm coding...");
}
}
//  Test our class 
var animal = new Animal('dummy'),
wayou = new Programmer('wayou');
animal.sayName(); //  The output  'My name is dummy'
wayou.sayName(); //  The output  'My name is wayou'
wayou.program(); //  The output  'I'm coding...' 

Enhanced object literals

Object literals have been enhanced, writing is more concise and flexible, and there is more you can do when defining objects. Specific manifestations are as follows:

1. You can define prototypes in object literals

2. You can define methods without using the function keyword

3. Call the parent method directly

As a result, object literals are more consistent with the class concepts mentioned earlier, making it easier to write object-oriented JavaScript.


//  Create objects from object literals 
var human = { 
breathe() {
console.log('breathing...');
}
};
var worker = { 
__proto__: human, //  Set the prototype of this object to human,  Equivalent to inheritance human
company: 'freelancer',
work() {
console.log('working...');
}
};
human.breathe(); //  The output  'breathing...'
//  Inherited by the call breathe methods 
worker.breathe(); //  The output  'breathing...' 

String template

The string template is relatively straightforward. ES6 allows the use of backquotes to create strings, which can contain the variable ${vraible} wrapped in dollar signs and curly braces. If you've ever used a backend strongly typed language like ES83en #, this should be familiar.


//  produce 1 A random number 
var num = Math.random();
//  Print this number to console 
console.log(`your num is ${num}`);

deconstruction

Automatically resolves values in arrays or objects. For example, if a function returns multiple values, it is common to return one object, with each value as an attribute of the object. In ES90en6, however, you can return an array by deconstructing it, and then the value of the array is automatically resolved into the variable that receives the value.


function getVal() {
return[1,2];
}
var [x,y] = getVal(), //  Deconstruction of the return value of a function 
console.log('x:' + x + ', y:' + y); //  Output: x:1, y:2
[name,,age] = ['wayou','male','secrect']; //  An array of deconstruction 
console.log('name:' + name + ', age:' + age); // Output: name:wayou, age:secrect 

Parameter default value, indefinite parameter, extended parameter

Default parameter value

You can now specify default values for parameters when defining functions, rather than using logic or operators.


function sayHello(name) {
//  The traditional way of specifying default parameters 
var name = name || 'dude';
console.log('Hello ' + name);
} 
sayHello(); //  Output: Hello dude
sayHello('Wayou'); //  Output: Hello Wayou
//  using ES6 Default parameters of the 
function sayHello2(name = 'dude') {
console.log(`Hello${name}`);
}
sayHello2(); //  Output: Hello dude
sayHello2('Wayou'); //  Output: Hello Wayou 

Uncertain parameters

An indeterminate argument is a function that takes a named argument and receives an indeterminate number of unnamed arguments. This is just a syntactic sugar, and in previous ES106en code we could have used the arguments variable for this purpose. The format of an indeterminate argument is three periods followed by a variable name that represents all of the indeterminate arguments.

For example, in the following example... x represents all parameters passed to the add function.


//  A function that adds up all its arguments 
function add(...x) {
return x.reduce((m,n) => m+n);
}
//  Passing an arbitrary number of arguments 
console.log(add(1,2,3)); //  Output: 6
console.log(add(1,2,3,4,5)); //  Output: 15 

Expand the parameters

Expansion arguments are another form of syntactic sugar that allows you to pass arrays or class arrays directly as arguments to a function without going through apply.


var people = ['Wayou','John','Sherlock'];
// sayHello Function original receiving 3 A single parameter person 1 , people 2 And the people 3
function sayHello(people1, people2, people3) {
console.log(`Hello${people1}, ${people2}, ${people3}`);
}
//  But we are going to 1 The array is passed as an extended parameter, which maps well to each individual parameter 
sayHello(...people); //  Output: Hello Wayou,John,Sherlock
//  Previously, if we needed to pass an array as an argument, we needed to use the function's apply methods 
sayHello.apply(null, people); //  Output: Hello Wayou,John,Sherlock 

let and const keywords

You can think of let as var, except that it defines variables within a certain range that they can only be used, and outside that range they are invalid. const is straightforward and is used to define constants, which are variables whose value cannot be changed.


for (let i=0; i<2; i++) {
console.log(i); //  The output : 0,1
}
console.log(i); //  Output: undefined, An error will be reported in strict mode  

for The of value traversal

We all know that the for loop is used to iterate over arrays, arrays of classes, or objects. The new for loop introduced in ES6 is similar, except that each loop provides a value instead of an sequence number.


var someArray = ["a","b","c"];
for (v of someArray) {
console.log(v); //  The output  a,b,c
} 

iterator, generator

1.iterator: This method returns an object {done,value}, which contains two attributes, a Boolean done and value containing any value

obj[@@iterator] = obj[@@iterator] = iterator [@@iterator]

3.generator: It is a special iterator. The inverse next method can take one argument and return the value depending on its constructor (generator function). generator also has one throw method

4.generator function: This is the constructor of generator. The yield keyword can be used within this function. Where yield is present, values can be passed to the outside world via next or throw methods of generator. The generator function is declared by function*

5.yield keyword: It can pause the execution of a function and then reenter the function to continue execution

The module

In the ES6 standard, JavaScript supports module natively. This concept of modularization of JS code into small pieces of different functionality was popularized in some 3-side specifications, such as the CommonJS and AMD schemas.

The code of different functions is written in different files, each module only needs to export the public interface part, and then can be used elsewhere through the way of module import.


//  The definition of a class 
class Animal {
// ES6 A new type of constructor 
constructor(name) {
this.name = name;
}
//  Instance methods 
sayName() {
console.log('My name is ' + this.name);
}
}
//  Class inheritance 
class Programmer extends Animal {
constructor(name) {
//  Initialize directly by calling the parent class constructor 
super(name);
}
program() {
console.log("I'm coding...");
}
}
//  Test our class 
var animal = new Animal('dummy'),
wayou = new Programmer('wayou');
animal.sayName(); //  The output  'My name is dummy'
wayou.sayName(); //  The output  'My name is wayou'
wayou.program(); //  The output  'I'm coding...' 
0

These are the new collection types that provide a more convenient way to get the value of a property without using hasOwnProperty to check whether a property belongs to the stereotype chain or to the current object as in the previous 1. At the same time, there are special get and set methods for adding and getting attribute values.


//  The definition of a class 
class Animal {
// ES6 A new type of constructor 
constructor(name) {
this.name = name;
}
//  Instance methods 
sayName() {
console.log('My name is ' + this.name);
}
}
//  Class inheritance 
class Programmer extends Animal {
constructor(name) {
//  Initialize directly by calling the parent class constructor 
super(name);
}
program() {
console.log("I'm coding...");
}
}
//  Test our class 
var animal = new Animal('dummy'),
wayou = new Programmer('wayou');
animal.sayName(); //  The output  'My name is dummy'
wayou.sayName(); //  The output  'My name is wayou'
wayou.program(); //  The output  'I'm coding...' 
1

I have commented the above code, so here is a step to explain it. For handler, it is the corresponding event happened to be listening object, the inside of the handler method is invoked, in the above example, we set up set processing function, shows that if we listen to the object's properties are changed, which is been set, then the handler is called, at the same time can know is which properties are changed by parameters, change for the sake of what value.

Symbols

We know that an object is really a collection of key-value pairs, and keys are usually strings. In addition to strings, we can now use values such as symbol as the object's key. Symbol is a primitive type, like numbers, strings, and booleans. It is not an object. Symbol is produced by calling the function symbol, which takes an optional name argument and returns a 1-only symbol. You can then use this return value as the object's key. Symbol can also be used to create private properties. The value of a property with symbol as the key is not directly accessible to outsiders.


//  The definition of a class 
class Animal {
// ES6 A new type of constructor 
constructor(name) {
this.name = name;
}
//  Instance methods 
sayName() {
console.log('My name is ' + this.name);
}
}
//  Class inheritance 
class Programmer extends Animal {
constructor(name) {
//  Initialize directly by calling the parent class constructor 
super(name);
}
program() {
console.log("I'm coding...");
}
}
//  Test our class 
var animal = new Animal('dummy'),
wayou = new Programmer('wayou');
animal.sayName(); //  The output  'My name is dummy'
wayou.sayName(); //  The output  'My name is wayou'
wayou.program(); //  The output  'I'm coding...' 
2

About ES6 new features to introduce so much, I hope to be helpful to you!


Related articles: