Introduction
ECMAScript 6 is the next standard for JavaScript and is in rapid development. The goal of ECMAScript 6 is to enable JavaScript to be used to write complex applications, function libraries and code automatic generators (code generators). The latest browsers already partially support the syntax of ECMAScript 6. ECMAScript 6 is currently basically the industry standard, and its popularity is much faster than ES5. The main reason is that modern browsers support ES6 quite quickly, especially Chrome and Firefox browsers, which already support most of the features in ES6.
1. let, const, and block scopes
Let allows creating block-level scopes. ES6 recommends using let in functions to define variables instead of var:
var a = 2;{ let a = 3; console.log(a); // 3}console.log(a); // 2Another way to declare variables that are 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 "const" is not static, 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:
Let keyword declared variables do not have the hoisting feature
The let and const declarations are valid only in the closest block (within curly braces)
When using the constant const declaration, use uppercase variables, such as: CAPITAL_CASING
const must be assigned when declared
2. Arrow Functions
In ES6, the arrow function is a short form of a function, using brackets to wrap the parameters, followed by an =>, followed by the function body:
var getPrice = function() { return 4.55;}; // Implementation with Arrow Functionvar getPrice = () => 4.55;It should be noted that the getPrice arrow function in the chestnut above uses a concise function body, which does not require a reture statement. The chestnut below uses a normal function body:
let arr = ['apple', 'banana', 'orange']; let breakfast = arr.map(fruit => { return fruit + 's';}); console.log(breakfast); // apples bananas orangesOf course, arrow functions are not just about making the code concise, but in the function this binding always points to the object itself. For details, you can take a look at the following chestnuts:
function Person() { this.age = 0; setInterval(function growUp() { // In non-strict mode, this of the growUp() function points to the window object this.age++; }, 1000);}var person = new Person();We often need to use a variable to save this and then reference it in the growUp function:
function Person() { var self = this; self.age = 0; setInterval(function growUp() { self.age++; }, 1000);}And using arrow functions can save this trouble:
function Person(){ this.age = 0; setInterval(() => { // |this| Point to person object this.age++; }, 1000);} var person = new Person();3. Function parameter default value
ES6 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..., whether it is Spread or Rest depends on the context.
When used in an iterator, it is a Spread operator:
function foo(x,y,z) { console.log(x,y,z);} let arr = [1,2,3];foo(...arr); // 1 2 3When used for function argument transfer, it is a 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 declaring abbreviated syntax when declaring object literals to initialize the definition methods of attribute variables and functions, and allows calculation operations in object properties:
function getCar(make, model, value) { return { // Abbreviation variable make, // Equivalent to make: make model, // Equivalent to model: model value, // Equivalent to value: value // The attribute can be calculated using expressions ['make' + make]: true, // Ignore `function` Keyword abbreviation object function depreciate() { this.value -= 2500; } };} let car = getCar('Barret', 'Lee', 40000); // output: {// make: 'Barret',// model:'Lee',// value: 40000,// makeBarret: true,// depreciate: function()// }6. Binary and octal literals
ES6 supports binary and octal literals, which can be converted to binary values by adding 0o or 0O in front of the number:
let oValue = 0o10;console.log(oValue); // 8 let bValue = 0b10; // Use `0b` or `0B` console.log(bValue); // 2
7. Object and array destruction
Deconstruction can avoid the generation of intermediate variables when object assignment:
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 68. Object Superclass
ES6 allows the use of super method in objects:
var parent = { foo() { console.log("Hello from the Parent"); }} var child = { foo() { super.foo(); console.log("Hello from the Child"); }} Object.setPrototypeOf(child, parent);child.foo(); // Hello from the Parent // Hello from the Child9. Template syntax and separator
There is a very concise way to assemble a bunch of strings and variables in ES6.
${ ... } is used to render a variable
` as a separator
let user = 'Barret';console.log(`Hi ${user}!`); // Hi Barret!10. for...of VS for...in
for...of is used to traverse an iterator, such as an array:
let nicknames = ['di', 'boo', 'punkeye'];nicknames.size = 3;for (let nickname of nicknames) { console.log(nickname);}Result: di, boo, punkeyefor...in is used to traverse properties in an object:
let nicknames = ['di', 'boo', 'punkeye'];nicknames.size = 3;for (let nickname in nicknames) { console.log(nickname);}Result: 0, 1, 2, size11. Map and WeakMap
There are two new data structure sets in ES6: Map and WeakMap. In fact, each object can be regarded as a map.
An object is composed of multiple key-val pairs. In a Map, any type can be used as the key of the object, such as:
var myMap = new Map(); var keyString = "a string", keyObj = {}, keyFunc = function () {}; // Set the value myMap.set(keyString, "value is associated with 'a string'"); myMap.set(keyObj, "value is associated with keyObj"); myMap.set(keyFunc, "value is associated with keyFunc"); myMap.size; // 3 // Get the value myMap.get(keyString); // "value is associated with 'a string'"myMap.get(keyObj); // "value is associated with 'a string'"myMap.get(keyObj); // "value is associated with 'a string'"myMap.get(keyObj); // "value Associate with keyObj "myMap.get(keyFunc); // "value associated with keyFunc"WeakMap
WeakMap is a map, but all its keys are weak references, which means that things in WeakMap are not considered when garbage collection, and you don’t have to worry about memory leaks when using it.
Another thing to note is that all keys of WeakMap must be objects. It only has 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); // truew.delete(o1); w.has(o1); // false12. Set and WeakSet
A Set object is a set of unrepeated values, and duplicate values will be ignored. The value types can be primitive and reference types:
let mySet = new Set([1, 1, 2, 2, 3, 3]);mySet.size; // 3mySet.has(1); // truemySet.add('strings');mySet.add({ a: 1, b:2 });You can traverse Set objects 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, the WeakSet object allows you to save weak references to objects in a collection, and 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); // truews.has(foo); // false, foo has not been added successfully ws.delete(window); // delete window object from combination ws.has(window); // false, window object has been deleted13. Class
There is class syntax in ES6. It is worth noting that the class here is not a new object inheritance model, it is just a syntactic sugar expression of the prototype chain.
The methods and properties of the constructor are defined in the function using the static keyword:
class Task { constructor() { console.log("task instantiated!"); } showId() { console.log(23); } static loadAll() { console.log("Loading all tasks.."); }} console.log(typeof Task); // functionlet task = new Task(); // "task instantiated!"task.showId(); // 23Task.loadAll(); // "Loading all tasks.."Inheritance and supersets in the class:
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 Porscheextends allows a subclass to inherit the parent class. 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 parent class's methods in the subclass methods, such as super.parentMethodName().
Read more about the class here.
There are a few points worth noting:
The declaration of the class will not be hoisting. If you want to use a Class, you must define it before using it, otherwise a ReferenceError error will be thrown.
Defining functions in classes does not require the use of function keywords
14. Symbol
Symbol is a new data type whose values are unique and immutable. The purpose of symbol proposed in ES6 is to generate a unique 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 in front of Symbol.
If it is used as an object's property, then this property will be inenumerable:
var o = { val: 10, [ Symbol("random") ]: "I'm a symbol",}; console.log(Object.getOwnPropertyNames(o)); // valIf you want to get the object symbol property, you need to use Object.getOwnPropertySymbols(o).
15. Iterators
The iterator allows access to an element of the data set every time an element is accessed. When the pointer points to the last element of the data set, the iterator exits. It provides the next() function to iterate over a sequence, which returns an object containing the done and value attributes.
In ES6, you can set a default traverser for the object through Symbol.iterator. No matter when the object needs to be traversed, the @@iterator method that executes its @@iterator method can return an iterator for obtaining the value.
The array is an iterator by default:
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 an iterator for an object through [Symbol.iterator]().
16. Generators
The Generator function is a new feature of ES6, which allows a function to return a traversable object to generate multiple values.
In use you will see the * 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. A Promise is an object waiting for asynchronous execution. When its execution is completed, its state will become resolved or rejected.
var p = new Promise(function(resolve, reject) { if (/* condition */) { // fulfilled successfully resolve(/* value */); } else { // error, rejected reject(/* reason */); }});Each Promise has a .then method, which accepts two parameters. The first is to handle the callback of the resolved state, and the other is to handle the callback of the rejected state:
p.then((val) => console.log("Promise Resolved", val), (err) => console.log("Promise Rejected", err));The above is an introduction to the quick start of ECMAScript 6 compiled for everyone. Friends who need it can learn and refer to it.