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

Example Analysis of es6 and es5

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

What is es6 and es5? I believe many inexperienced people are at a loss about this. Therefore, this article summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

ES5 is: strict mode, Array addition method, Object method; ES6 is: assignment deconstruction, parameter packaging, array expansion, arrow function, string template, iterator, generator, array expansion, block-level scope, object literals, and so on. The operating environment of this tutorial: windows7 system, Dell G3 computer.

What is ES5?

As the fifth version of ECMAScript (the fourth version is obsolete because of its complexity), browser support can be seen in the first picture, with the following added features.

1. Strict mode

Strict mode, limit some usage, 'use strict'

2. Array addition method

Added every, some, forEach, filter, indexOf, lastIndexOf, isArray, map, reduce, reduceRight methods PS: there are other methods Function.prototype.bind, String.prototype.trim, Date.now

3. Object method

Object.getPrototypeOf

Object.create

Object.getOwnPropertyNames

Object.defineProperty

Object.getOwnPropertyDescriptor

Object.defineProperties

Object.keys

Object.preventExtensions / Object.isExtensible

Object.seal / Object.isSealed

Object.freeze / Object.isFrozen

PS: just talk about what there is, not what it is.

What is ES6?

ECMAScript6 provides a large number of new features while ensuring backward compatibility. The current browser compatibility is as follows: ES6 features:

1. Block-level scope keyword let, constant const

two。 Abbreviation for attribute assignment of literal amount of object (property value shorthand)

Var obj = {/ / _ proto__ _ proto__: theProtoObj, / / Shorthand for 'handler: handler' handler, / / Method definitions toString () {/ / Super calls return "d" + super.toString ();}, / / Computed (dynamic) property names [' prop_' + (() = > 42) ()]: 42}

3. Assignment deconstruction

Let singer = {first: "Bob", last: "Dylan"}; let {first: f, last: l} = singer; / / equivalent to f = "Bob", l = "Dylan" let [all, year, month, day] = / ^ (dddd)-(dd)-(dd) $/ .exec ("2015-10-25"); let [x, y] = [1,2,3]; / x = 1, y = 2

4. Function parameters-default values, parameter packaging, array expansion (Default, Rest, Spread)

/ / Defaultfunction findArtist (name='lu', age='26') {...} / / Restfunction f (x,... y) {/ / y is an Array return x * y.hello;} f (3, "hello", true) = = 6//Spreadfunction f (x, y, z) {return x + y + z;} / / Pass each elem of array as argumentf (.

5. Arrow function Arrow functions

(1)。 Simplified code form, default return expression result.

(2)。 Automatically bind the semantic this, that is, the this when defining the function. As in the example above, this is used in the anonymous function parameters of forEach.

6. String template Template strings

Var name = "Bob", time = "today"; `Hello ${name}, how are you ${time}? `/ / return "Hello Bob, how are you today?"

7. Iterators (iterator) + for..of iterator has a next method, and the call returns:

(1)。 Returns an element of the iterative object: {done: false, value: elem}

(2)。 If you have reached the end of the iterative object: {done: true, value: retVal}

For (var n of ['axiomaginomagnesia']) {console.log (n);} / / print a, b, c

8. Generator (Generators)

9.Class

Class, with constructor, extends, and super, is essentially syntactic sugar (it doesn't affect the functionality of the language, but it's easier for programmers to use).

Class Artist {constructor (name) {this.name = name;} perform () {return this.name + "performs";}} class Singer extends Artist {constructor (name, song) {super.constructor (name); this.song = song;} perform () {return super.perform () + "[" + this.song + "]" }} let james = new Singer ("Etta James", "At last"); james instanceof Artist; / / truejames instanceof Singer; / / truejames.perform (); / / "Etta James performs [At last]"

10.Modules

The built-in module function of ES6 draws lessons from the respective advantages of CommonJS and AMD: (1). It has the characteristics of simplified syntax, unique export (single exports) and circular dependency (cyclic dependencies) of CommonJS. (2)。 Similar to AMD, it supports asynchronous loading and configurable module loading.

/ / lib/math.jsexport function sum (x, y) {return x + y;} export var pi = 3.141593 math.pi / app.jsimport * as math from "lib/math"; alert ("2 π =" + math.sum (math.pi, math.pi)); / / otherApp.jsimport {sum, pi} from "lib/math"; alert ("2 π =" + sum (pi, pi)) Module Loaders:// Dynamic loading-'System' is default loaderSystem.import (' lib/math') .then (function (m) {alert ("2 π =" + m.sum (m.pi, m.pi));}); / / Directly manipulate module cacheSystem.get ('jquery'); System.set (' jquery', Module ({$: $})); / / WARNING: not yet finalized

There are four collection types: 11.Map + Set + WeakMap + WeakSet. Objects with WeakMap and WeakSet as property keys will be recycled and released if there are no other variables referencing them.

/ / Setsvar s = new Set (); s.add ("hello"). Add ("goodbye"). Add ("hello"); s.size = = 2 hello. Has ("hello") = = true;// Mapsvar m = new Map (); m.set ("hello", 42); m.set (s, 34); m.get (s) = 34 TacronA WeakMapvar wm = new WeakMap (); wm.set (s, {extra: 42}); wm.size = = undefined// Weak Setsvar ws = new WeakSet () Ws.add ({data: 42}); / / Because the added object has no other references, it will not be held in the set

12.Math + Number + String + Array + Object APIs some new API

Number.EPSILONNumber.isInteger (Infinity) / / falseNumber.isNaN ("NaN") / / falseMath.acosh (3) / / 1.762747174039086Math.hypot (3,4) / / 5Math.imul (Math.pow (2,32)-1, Math.pow (2,32)-2) / / 2 "abcde" .repeat ("cd") / / true "abc" .repeat (3) / / "abcabcabc" Array.from (document.querySelectorAll ('*')) / / Returns a real ArrayArray.of (1,2) 3) / / Similar to new Array (...), but without special one-arg behavior [0,0,0] .fill (7,1) / / [0,2,3] .find (x = > x = 3) / / 3 [1,2,3] .findIndex (x = > x = = 2) / / 1 [1,2,3,4,5] .copythin (3,0) / [1,2,3,1,2] ["a", "b" "c"] .entries () / / iterator [0, "a"], [1, "b"], [2, "c"] ["a", "b", "c"] .keys () / / iterator 0,1,2 ["a", "b", "c"] .values () / / iterator "a", "b", "c" Object.assign (Point, {origin: new Point (0)})

13. Proxies uses Proxy to listen to the operation of the object, and then can do something accordingly.

Var target = {}; var handler = {get: function (receiver, name) {return `Hello, ${name}! `;}; var p = new Proxy (target, handler); p.world = = 'Hello, Worldwide'

Listenable operations: get, set, has, deleteProperty, apply, construct, getOwnPropertyDescriptor, defineProperty, getPrototypeOf, setPrototypeOf, enumerate, ownKeys, preventExtensions, isExtensible.

14.Symbols Symbol is a basic type. Symbol is generated by calling the symbol function, which receives an optional name argument, and the symbol returned by this function is unique.

Var key = Symbol ("key"); var key2 = Symbol ("key"); key = = key2 / / false

15.Promises

Promises is an object that handles asynchronous operations, and after using the Promise object, you can organize the code in a chained way to make the code more intuitive (similar to jQuery's deferred object).

Function fakeAjax (url) {return new Promise (function (resolve, reject) {/ / setTimeouts are for effect, typically we would handle XHR if (! url) {return setTimeout (reject, 1000);} return setTimeout (resolve, 1000);});} / no url, promise rejectedfakeAjax (). Then (function () {console.log ('success');}, function () {console.log (' fail');}) After reading the above, have you mastered the methods of es6 and es5? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

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