Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the new features of es6

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the relevant knowledge of "what are the new features of es6". The editor shows you the operation process through an actual case, and the operation method is simple, fast and practical. I hope this article "what are the new features of es6" can help you solve the problem.

Es6 was released in June 2015. Es6, whose full name is "ECMAScript6", is the standard of the JavaScript language officially released in June 2015. its official name is ECMAScript2015 (ES2015). Because it is the sixth version of ECMAScript, it can be referred to as es6 for short.

The operating environment of this tutorial: windows7 system, ECMAScript version 6, Dell G3 computer.

Brief introduction of "es"

Es, whose full name is "ECMAScript", is a general scripting language implemented according to the ECMA-262 standard. The ECMA-262 standard mainly defines the syntax, type, statement, keyword, reserved word, operator, object and other parts of the language. At present, the latest version of ECMAScript is ECMAScript6 (referred to as "ES6").

Every time I see ES followed by a number, it is a different version of ECMAScript.

Es6/ ES2015

Es6, whose full name is ECMAScript6 (the sixth version of ECMAScript), is the standard for the JavaScript language officially released in June 2015, officially known as ECMAScript 2015 (ES2015). Its goal is to enable the JavaScript language to be used to write complex large-scale applications and become an enterprise development language.

ECMAScript 6 has basically become an industry standard, and its popularity is much faster than that of ES5. The main reason is that modern browsers support ES6 very quickly, especially Chrome and Firefox browsers, which already support most of the features in ES6.

New features of ES6:

1. Let, const and block scope

Let allows you to create 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 the 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, that is, the "constant" is not immutable, such as:

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

There are a few points to note:

Variables declared by the let keyword do not have variable promotion (hoisting) features

Let and const declarations are valid only in the nearest block (in curly braces)

When using a constant const declaration, use uppercase variables, such as CAPITAL_CASING

Const must be assigned when declaring

two。 Arrow function (Arrow Functions)

In ES6, the arrow function is an abbreviated form of a function, using parentheses to wrap parameters, followed by a = >, 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 above example uses a concise function body, which does not require a return statement. The following example uses the normal function body:

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

Of course, the arrow function doesn't just make the code concise, the this binding in the function always points to the object itself. Take a look at the following examples:

Function Person () {this.age = 0; setInterval (function growUp () {/ / in non-strict mode, the 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 hold the 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 hassle:

Function Person () {this.age = 0; setInterval () = > {/ / | this | pointing to the person object this.age++;}, 1000);} var person = new Person ()

3. Default value of function parameter

ES6 allows you to set default values for function parameters:

Let getFinalPrice = (price, tax=0.7) = > price + price * tax;getFinalPrice

4. Spread / Rest operator

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

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

Function foo {console.log (x recital z);} let arr = [1meme 2je 3]; foo (.arr); / / 1 2 3

When used to pass parameters to a function, 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 you to use abbreviated syntax when declaring object literals, to initialize the definition methods of property variables and functions, and to perform calculations in object properties:

Function getCar (make, model, value) {return {/ / abbreviated variable make, / / equivalent to make: make model, / / equivalent to model: model value, / / equivalent to value: value / / attribute can be calculated using expressions ['make' + make]: true, / / ignore `function` keyword abbreviated object function depreciate () {this.value-= 2500 }};} let car = getCar ('Barret',' Lee', 40000); / / output: {/ / make: 'Barret',// model:'Lee',// value: 40000 Legend / makeBarret: true,// depreciate: [Function: depreciate] / /}

6. Binary and octal literals

ES6 supports both binary and octal literals, which can be converted to octal values by adding 0o or 0O to the number:

Let oValue = 0o10 console.log (oValue); / 8 let bValue = 0b10; / / binary uses `0b` or `0B`console.log (bValue); / / 2

7. Deconstruction of objects and arrays

Deconstruction avoids the creation of intermediate variables when an object is assigned:

Function foo () {return [1je 2jue 3];} let arr = foo (); / / [1JI 2jue 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} = bar (); console.log (x, y, z); / / 4 5 6

8. Object superclass

ES6 allows the use of the super method in an object:

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 Child

9. Template syntax and delimiter

There is a very concise way to assemble a bunch of strings and variables in ES6.

${.} to render a variable

`as a delimiter

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, punkeye

For...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, size

11. Map and WeakMap

Two new sets of data structures in ES6: Map and WeakMap. Virtually every object can be thought of as a Map.

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

Var myMap = new Map (); var keyString = "a string", keyObj = {}, keyFunc = function () {}; / / set 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 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 a Map, except that all its key 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 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 ('averse,' 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) / / false

12. Set and WeakSet

The Set object is a set of values that are not duplicated, the duplicate values are ignored, and the value types can be primitive and reference types:

Let mySet = new Set ([1, 1, 2, 2, 3]); mySet.size; / / 3mySet.has (1); / / truemySet.add ('strings'); mySet.add ({a: 1, bju 2})

You can traverse the Set object 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, you can 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 did not add ws.delete (window) successfully; / / remove window object ws.has (window) from the union; / / false, window object has been deleted

13. Class

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

Define the methods and properties of the constructor using the static keyword in the function:

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 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 a subclass to inherit the parent class, and it is important to note that the super () function needs to be executed in the subclass's constructor function.

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

Read more about classes here.

There are several points worth noting:

The declaration of the class will not hoisting. If you want to use a Class, you must define it before using it, otherwise an error of ReferenceError will be thrown

You do not need to use the function keyword to define functions in a class

14. Symbol

Symbol is a new data type whose values are unique and immutable. The purpose of symbol in ES6 is to generate a unique identifier, but you cannot access it:

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

Note that the new operator cannot be used before Symbol.

If it is used as a property of an object, then this property cannot be enumerated:

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 you to access 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 iterate through a sequence, which returns an object that contains the done and value properties.

In ES6, you can set a default traversal for an object through Symbol.iterator, and whenever the object needs to be traversed, the @ @ iterator method executes it to return an iterator to get the value.

An array is an iterator by default:

Var arr = [11itr.next 1213]; 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 object's iterator through [Symbol.iterator] ().

16. Generators

The Generator function is a new feature of ES6 that allows traverable objects returned by a function to generate multiple values.

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

Function * infiniteNumbers () {var n = 1; while (true) {yield nails;}} 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 a yield is executed, the value returned becomes the next value of the iterator.

17. Promises

ES6 has native support for Promise. A Promise is an object waiting to be executed asynchronously. When its execution is complete, 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 * /);}})

Every Promise has a .then method that takes two arguments, the first one to handle the callback of the resolved state and the other to handle the callback of the rejected state:

P.then ((val) = > console.log ("Promise Resolved", val), (err) = > console.log ("Promise Rejected", err)); so much for the introduction of "what are the new features of es6". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report