ECMAScript6 Quick Start Raiders

  • 2021-07-04 17:57:59
  • OfStack

Brief introduction

ECMAScript 6 is the next standard of JavaScript and is under rapid development. The goal of ECMAScript 6 is to enable JavaScript to be used to write complex applications, function libraries and automatic generators of code (code generator). The latest browsers have partially supported the syntax of ECMAScript 6, and ECMAScript 6 has basically become the industry standard at present. Its popularization speed is much faster than ES5, mainly because modern browsers support ES6 very quickly, especially Chrome and Firefox browsers, which already support most of the features in ES6.

1. let, const, and block scopes

let allows the creation of block-level scopes, and ES6 recommends using let to define variables in functions instead of var:


var a = 2;
{
 let a = 3;
 console.log(a); // 3
}
console.log(a); // 2

Another variable declaration method that is also valid at block level scope is const, which can declare a constant. In ES6, the constant declared by const is similar to a pointer, which points to a reference, which means that this "constant" is not immutable, such as:


{
 const ARR = [5,6];
 ARR.push(7);
 console.log(ARR); // [5,6,7]
 ARR = 10; // TypeError
}

There are a few points to note:

The variables declared by the let keyword do not have the variable promotion (hoisting) feature

let and const declarations are valid only in the nearest 1 block (within curly braces)

When declaring with the constant const, use uppercase variables, such as CAPITAL_CASING

const must be assigned a value when declared

2. Arrow function (Arrow Functions)

In ES6, the arrow function is a shorthand for the function, wrapping the parameter in parentheses, followed by a = > Followed by the function body:


var getPrice = function() {
 return 4.55;
};
 
// Implementation with Arrow Function
var getPrice = () => 4.55;

It should be noted that the getPrice arrow function in the above chestnut uses a concise function body, which does not need an reture statement. The following chestnut uses a normal function body:


let arr = ['apple', 'banana', 'orange'];
 
let breakfast = arr.map(fruit => {
 return fruit + 's';
});
 
console.log(breakfast); // apples bananas oranges

Of course, the arrow function doesn't just keep the code simple. The this in the function is always bound and always points to the object itself. You can look at the following chestnuts:


function Person() {
 this.age = 0;
 
 setInterval(function growUp() {
 //  In the non-strict mode, growUp()  Functional  this  Point  window  Object 
 this.age++;
 }, 1000);
}
var person = new Person();

We often need to use a variable to hold this, and then refer to it in the growUp function:


function Person() {
 var self = this;
 self.age = 0;

 setInterval(function growUp() {
 self.age++;
 }, 1000);
}

Using the arrow function can save this trouble:


function Person(){
 this.age = 0;
 
 setInterval(() => {
 // |this|  Point  person  Object 
 this.age++;
 }, 1000);
}
 
var person = new Person();

3. Default values for function arguments

ES 6 allows you to set default values for function parameters:


let getFinalPrice = (price, tax=0.7) => price + price * tax;
getFinalPrice(500); // 850

4. Spread/Rest Operator

The Spread/Rest operator refers to..., and whether it is Spread or Rest depends on the context.

When used in an iterator, it is an Spread operator:


function foo(x,y,z) {
 console.log(x,y,z);
}
 
let arr = [1,2,3];
foo(...arr); // 1 2 3

When used for function parameterization, it is an Rest operator:


function foo(...args) {
 console.log(args);
}
foo( 1, 2, 3, 4, 5); // [1, 2, 3, 4, 5]

5. Object lexical extension

ES6 allows declarations to use abbreviated syntax for object literals, initialize the definition methods of property variables and functions, and allow computation operations in object properties:


{
 const ARR = [5,6];
 ARR.push(7);
 console.log(ARR); // [5,6,7]
 ARR = 10; // TypeError
}
0

6. Binary and Octal literals

ES6 supports binary and octal literals, which can be converted to binary values by preceding a number with either 0o or 0O:


let oValue = 0o10;
console.log(oValue); // 8
 
let bValue = 0b10; // 2 Binary usage  `0b`  Or  `0B`
console.log(bValue); // 2

7. Object and Array Deconstruction

Deconstruction can avoid generating intermediate variables when objects are assigned:


function foo() {
 return [1,2,3];
}
let arr = foo(); // [1,2,3]
 
let [a, b, c] = foo();
console.log(a, b, c); // 1 2 3
 
function bar() {
 return {
 x: 4,
 y: 5,
 z: 6
 };
}
let {x: x, y: y, z: z} = bar();
console.log(x, y, z); // 4 5 6

8. Object superclasses

ES6 allows the use of super methods in objects:


{
 const ARR = [5,6];
 ARR.push(7);
 console.log(ARR); // [5,6,7]
 ARR = 10; // TypeError
}
3

9. Template syntax and separators

In ES6, there is a 10-point concise way to assemble a stack of strings and variables.

${...} is used to render 1 variable
` As a separator


{
 const ARR = [5,6];
 ARR.push(7);
 console.log(ARR); // [5,6,7]
 ARR = 10; // TypeError
}
4

10. for...of VS for...in

for... of is used to traverse 1 iterator, such as an array:


{
 const ARR = [5,6];
 ARR.push(7);
 console.log(ARR); // [5,6,7]
 ARR = 10; // TypeError
}
5

for... in is used to traverse properties in objects:


{
 const ARR = [5,6];
 ARR.push(7);
 console.log(ARR); // [5,6,7]
 ARR = 10; // TypeError
}
6

11. Map and WeakMap

Two new sets of data structures in ES6: Map and WeakMap. In fact, each object can be regarded as an Map.

An object consists of multiple key-val pairs. In Map, any type can be used as an key of an object, such as:


var myMap = new Map();
 
var keyString = "a string",
 keyObj = {},
 keyFunc = function () {};
 
//  Setting value 
myMap.set(keyString, "value  And  'a string'  Association ");
myMap.set(keyObj, "value  And  keyObj  Association ");
myMap.set(keyFunc, "value  And  keyFunc  Association ");
 
myMap.size; // 3
 
//  Get a value 
myMap.get(keyString); // "value  And  'a string'  Association "
myMap.get(keyObj); // "value  And  keyObj  Association "
myMap.get(keyFunc); // "value  And  keyFunc  Association "

WeakMap

WeakMap is an Map, but all its key are weak references, which means that things in WeakMap are not considered for garbage collection, and there is no need to worry about memory leakage when using it.

Another point to note is that all key of WeakMap must be objects. It has only four methods delete (key), has (key), get (key) and set (key, val):


let w = new WeakMap();
w.set('a', 'b'); 
// Uncaught TypeError: Invalid value used as weak map key
 
var o1 = {},
 o2 = function(){},
 o3 = window;
 
w.set(o1, 37);
w.set(o2, "azerty");
w.set(o3, undefined);
 
w.get(o3); // undefined, because that is the set value
 
w.has(o1); // true
w.delete(o1);
w.has(o1); // false

12. Set and WeakSet

An Set object is a set of non-duplicate values, duplicate values are ignored, and the value types can be primitive and reference types:


{
 const ARR = [5,6];
 ARR.push(7);
 console.log(ARR); // [5,6,7]
 ARR = 10; // TypeError
}
9

Set objects can be iterated through forEach and for... of:


mySet.forEach((item) => {
 console.log(item);
 // 1
 // 2
 // 3
 // 'strings'
 // Object { a: 1, b: 2 }
});
 
for (let value of mySet) {
 console.log(value);
 // 1
 // 2
 // 3
 // 'strings'
 // Object { a: 1, b: 2 }
}

Set also has delete () and clear () methods.

WeakSet

Similar to WeakMap, WeakSet objects allow you to hold weak references to objects in a collection, while objects in WeakSet are only allowed to appear once:


var ws = new WeakSet();
var obj = {};
var foo = {};
 
ws.add(window);
ws.add(obj);
 
ws.has(window); // true
ws.has(foo); // false, foo  No Success Added 
 
ws.delete(window); //  Remove from Combination  window  Object 
ws.has(window); // false, window  Object has been deleted 

13. Classes

class syntax is found in ES6. It is worth noting that class here is not a new object inheritance model, it is just a syntactic representation of prototype chain.

Function uses the static keyword to define the methods and properties of the constructor:


class Task {
 constructor() {
 console.log("task instantiated!");
 }
 
 showId() {
 console.log(23);
 }
 
 static loadAll() {
 console.log("Loading all tasks..");
 }
}
 
console.log(typeof Task); // function
let task = new Task(); // "task instantiated!"
task.showId(); // 23
Task.loadAll(); // "Loading all tasks.."

Inheritance and supersets in classes:


class Car {
 constructor() {
 console.log("Creating a new car");
 }
}
 
class Porsche extends Car {
 constructor() {
 super();
 console.log("Creating Porsche");
 }
}
 
let c = new Porsche();
// Creating a new car
// Creating Porsche

extends allows 1 subclass to inherit from the parent class, and it should be noted that the super () function needs to be executed in the constructor function of the subclass.

Of course, you can also call the method of the parent class in the method of the subclass, such as super. parentMethodName ().

Read more about classes here.

There are several points worth noting:

Class declaration does not promote (hoisting). If you want to use an Class, you must define it before using it, otherwise an ReferenceError error will be thrown
You do not need to use function keywords to define functions in classes

14. Symbol

Symbol is a new data type whose value is only 1 and immutable. symbol is proposed in ES6 to generate a 1-only identifier, but you cannot access this identifier:


var sym = Symbol( "some optional description" );
console.log(typeof sym); // symbol

Note that the new operator cannot be used before Symbol here.

If it is used as a property of 1 object, then this property will be non-enumerable:


var o = {
 val: 10,
 [ Symbol("random") ]: "I'm a symbol",
};
 
console.log(Object.getOwnPropertyNames(o)); // val

If you want to get the object symbol property, you need to use Object. getOwnPropertySymbols (o).

15. Iterator (Iterators)

The iterator allows access to one element of the data set at a time, and exits when the pointer points to the last element of the data set. It provides the next () function to traverse a sequence, and this method returns an object containing done and value properties.

In ES6, you can set the default iterator for an object through Symbol. iterator. Whenever an object needs to be traversed, executing its @ @ iterator method can return an iterator for getting a value.

The array defaults to one iterator:


var arr = [11,12,13];
var itr = arr[Symbol.iterator]();
 
itr.next(); // { value: 11, done: false }
itr.next(); // { value: 12, done: false }
itr.next(); // { value: 13, done: false }
 
itr.next(); // { value: undefined, done: true }

You can customize the iterator for 1 object through [Symbol. iterator] ().

16. Generators

The Generator function is a new feature of ES6 that allows a single function to return a traversible object that generates multiple values.

In use, you will see * syntax and a new keyword yield:


function *infiniteNumbers() {
 var n = 1;
 while (true){
 yield n++;
 }
}
 
var numbers = infiniteNumbers(); // returns an iterable object
 
numbers.next(); // { value: 1, done: false }
numbers.next(); // { value: 2, done: false }
numbers.next(); // { value: 3, done: false }

Each time yield is executed, the returned value becomes the next value of the iterator.

17. Promises

ES6 has native support for Promise. An Promise is an object waiting to be executed asynchronously. When it is executed, its state will change to resolved or rejected.


var p = new Promise(function(resolve, reject) { 
 if (/* condition */) {
 // fulfilled successfully
 resolve(/* value */); 
 } else {
 // error, rejected
 reject(/* reason */); 
 }
});

Every Promise has one. then method, which takes two parameters, the first is a callback that handles the state of resolved, and the first is a callback that handles the state of rejected:


p.then((val) => console.log("Promise Resolved", val),
 (err) => console.log("Promise Rejected", err));

The above is a brief introduction of ECMAScript6, which is arranged for everyone. Friends who need it can learn and refer to it.


Related articles: