ES5 ~ ES10 summary

  Long time no write a summary blog, this time around are doing study notes on Git. Immediately to the end of the year, it is time to do some knowledge summarized. (Past and)

  JavaScript is a very interesting language, such as the name of Li Dai Java, and Java but it does not matter. JS language itself is weak type (data type implicit conversion), like Java, C, etc., there are strict requirements for the data type. The advantage of this characteristic is that data manipulation and the use of very flexible, resulting disadvantage is likely to have a lot of problems and based on this characteristic skill needs in mind, it makes up with a relatively complex. JS development and relatively late start some belong to some specifications and features are constantly have to develop and improve. Moreover, recent new features and new version updates faster and faster.

  JS development process, from the late 20th century slowly began to specification. In 1997 the first edition published in 1998 as an international standard format modify, 1999 regular scope chain, new control instructions, exception handling, error definitions, data output formatting, etc., JS quick start widespread use. In 2009, we added a strict mode in order to regulate and correct the fuzzy front concept, increasing the getters, setters, JSON, etc. 2011 release ES5 standard. Here begins summary from this version. In fact, there are many versions about JS different terminologies, such as here that ES is an abbreviation of ECMAScript, ES5 called ECMAScript5.1, and even ISO / IECxxx international standard version, you can even call ES2011. It is called too much, but will want to remember their practice headache, so we simply recognize ES5 only in recent years this way of talking.

ES5

  ES5 was released in 2011, the main new features are (in fact, the standard version is not the official version in 2009, so the 2009 version several features that can be counted as ES5 properties, such as strict mode, JSON, etc., here not elaborate):

  1. JSON, parse and stringify mainly two methods commonly used;
  2. Object extensions, Object.create (prototype, [descriptors]), Object.defineProperties (object, descriptors) (defineProperty single), and getPrototypeOf, getOwnPropertyDescriptor, getOwnPropertyNames, seal, freeze, preventExtensions (which is a set of three), and the like Keys common properties and methods;
  3. Array prototype expansion, Array prototype of the prototype increased isArray, indexOf, lastIndexOf, every, some, forEach, map, filter, reduce, reduceRight (7 which is traversed correlation) or the like;
  4. Function Prototype extension, new bind method, comparing the reference memory call and apply; (all of which are used to make this change point, the first parameter is the target object, and bind the same parameters in the form of call and to be more parameters, bind a function return, Call is executed immediately and apply, apply two parameters, the second parameter is an array of parameters behind)

ES6

  ES6 larger changes are more than ES5 Update, 2015 release. The main part as follows:

1. The block-level scope statement, and the let const, var functions such as, but are block-level scope, relatively easy to distinguish;

2. Class Class, prior to using the constructor ES6 are combined with other similar methods to implement a prototype chain instance object class can now be implemented directly, as an example;

 1 // Old
 2 function Person(name, age) {
 3   this.name = name
 4   this.age = age    
 5 }
 6 Person.prototype.say = function() {
 7   return 'Name:' + this.name + ',age:' +this.age  
 8 }
 9 // New
10 class Person {
11   constructor(name, age) {
12      this.name = name
13      this.age = age  
14    }
15   say()   {
16       return 'Name:' + this.name + ',age:' +this.age  
17     }
18 }

3. Arrow function, define how soon the anonymous function will be reduced, => instead of the function key, mainly for local anonymous function, do not own this, arguments, super, new.target, such as arr.forEach (item => {});

4. The default parameter values, which can easily specify default values ​​for parameters when defining a method as const funcA = (age = 0) => {};

The template string, string concatenation mainly used, in conjunction with the situation using `$ {}, as const name = 'xxx'; alert (` Name: $ {name} `);

6. destructuring assignment, by deconstructing the assignment, or assign attribute values ​​extracted from the object or the array to the other variables, to explain more obscure, such as the exchange of the values ​​of two variables [a, b] = [b, a], there is no need then defined using conventional processing method of the third intermediate value, it can be regarded as a subvert the traditional;

7.Module modular before for ES6, mainly modular CommonJS AMD and a custom class rules, standards for ES6 increased modularity, the following example;

 1 // Old
 2 // circle.js
 3 const {PI} = Math
 4 exports.area = (r) => PI * r ** 2
 5 exports.circumference = (r) => PI * r * 2
 6 
 7 // index.js
 8 const circle = require('./circle.js')
 9 console.log(`圆形面积:${circle.area(2)}`)
10 
11 // New
12 // circle.js
13 const {PI} = Math
14 export const area = (r) => PI * r ** 2
15 export const circumference = (r) => PI * r * 2
16 
. 17  // The index.js 
18 is Import Area} = { './circle.js'
 . 19 the console.log ( `circular area: $ {area (2)} `)

8. Extended operator (three points), only for iterables, as a conventional method will be the sum of the number 3, number 3 if you are adding an array, using a conventional writing method .apply (null, arr), extended operator may use direct methods (ARR ...) is performed;

9. abbreviated object properties, if const a = '1'; const obj = {a: a}, can be written const obj = {a}, where the variable name and attribute name to use the same character;

10.Promise, which more fun, and the general approach is to use asynchronous callbacks before, the arrival of Promise, asynchronous and chained calls with the new direction. Here it is easy to wander on the order of execution, because JS is executed sequentially, and have a Promise, callback even await / async to disrupt the order of execution of asynchronous, often liked to ask. In addition Promise to solve the callback area wording that is nested, such as the most common ajax request when the request returns to rely on the front, the traditional wording is nested ajax, now writing Promise.then, then to the Senate where that is is a request to return the front, which is why Promise and then often appear together, and then actually return when the return is a Promise, shaped like Promise.resolve () packaging, such as: Promise.resolve (1) .then ( res => {// res is 1 return 2}) then (res => {// res is 2});. // TODO - summary awite / async and Promise

11.for ... of, iterables (Array, Map, Set, String, TypedArray, arguments) iteration, as const arr = [1,2,3]; for (const el of arr) {xxx};

12.symble type, a new basic data types, such as const a = Symble (22), does not support the use of new generation, is to generate unique values, such as Symbol (1) == Symbol (1) for false;

13. iterator (Interator) / generator (Generator), the main function is to implement a custom iteration, the real use to the place is not much to see at present, it was seen in conjunction promise to achieve a similar effect await / async, but not as good as why directly going around, it is not described in detail here, and so have to do a detailed comparison scenario applies, briefly, at a next visit (), * and keyword yield, for example as follows;

// stage1 
function * makeRangeIterator (Start = 0, End = Infinity, STEP =. 1 ) {
     for (I = Start the let; I <End; = I + STEP) { 
        the yield I; 
    } 
} // Found close function and * no difference against method names; the yield plays a similar effect return 
var a = makeRangeIterator (1, 10, ) 
a.next () // {value:. 1, DONE: to false} 
a.next () // {value :. 3, DONE: to false} 

// stage2 
function * createIterator (items) {
     for (the let I = 0; I <items.length; I ++ ) { 
        the yield items [I] 
    } 
} 
the let Iterator= createIterator([1,2,3])
console.log(iterator.next()); // { value:1, done: false }

// stage3
function *createIterator(){
    yield 1
    yield 2
    yield 3
}
let iterator = createIterator()

console.log(iterator.next().value) //1

14.Set / WeakSet, Set type of object allows the storage of any type of unique values ​​for its uniqueness, can be used as a weight to an array [... new Set (arr)], WeakSet similar, but only store the object reference, and the element If there are no references to other objects or property recovered will be released, and the object can not be enumerated, both have add, has, delete, clear methods;

Type distinction 15.Map/WeakMap,Map stored key-value pair, and the key value can be any value or object, Map type methods set (key, value), and get, has, delete, clear, etc., WeakMap and Map and Similarly 14, key can only be an object;

16.Proxy / Reflect, agents reflection, the effect is to create the feeling of listening and watcher realize intercept js, meta-programming, syntax - var proxy = new Proxy (target, handler), handler can contain set, get, apply, has, etc. etc., Reflect correspondence therewith as - Reflect.has (Object, 'assign'), a data listener example implementation;

 1 const observe = (data, callback) => {
 2       return new Proxy(data, {
 3             get(target, key) {
 4                 return Reflect.get(target, key)
 5             },
 6             set(target, key, value, proxy) {
 7                   callback(key, value);
 8                   target[key] = value;
 9                     return Reflect.set(target, key, value, proxy)
10             }
11       })
12 }
13 
14 const FooBar = { open: false };
15 const FooBarObserver = observe(FooBar, (property, value) => {
16   property === 'open' && value 
17           ? console.log('FooBar is open!!!') 
18           : console.log('keep waiting');
19 });
20 console.log(FooBarObserver.open) // false
21 FooBarObserver.open = true // FooBar is open!!!

17.Regex extended object, add modifiers regular i, iu, y, (u is unicode mode), the new attribute - flag view property modifier, Sticky property corresponding to y, to realize a method invocation string RegExpmethods ( ?) - TODO regular need a solid;

18.Math expansion, 0b / 0B represents a binary, 0o / 0O represents octal, Number.EPSILON (minimum accuracy) and some constants, Number extension method (.parseInt (), parseFloat (), isFinite (), isNaN ( ), isInteger (), isSafeInteger ()), Math extension method, (trunc () - returns the integer part, sign () returns a value of positive and negative types 0, cbrt () cube root, clz32 () 32-bit unsigned integer, fround ( ) 32-bit single precision floating point number, imul () returns multiply two numbers, hypot () and all values ​​of the square root, expm1 () e power of n -1, log1p () is equal to Math.log (1 + n), log10 (), log2 (), all hyperbolic sine trigonometric functions - in the original name with a trigonometric function such as h sinh ());

19.Array extended, form (such as console.log (Array.from ([1, 2 , 3], x => x + x)) // [2, 4, 6]) (console.log (Array.from ( 'foo')) // [ "f", "o", "o"]) and the source parameter handler, of (such as Array.of (3) // [3] ; Array.of (1,2 ) // [1,2]), copyWithin -  array . copyWithin ( target , Start , End ), the latter two are optional, defaults to the tail head, without changing the length of the array, only the replacement value, such as

var fruits = ["Banana", "Orange", "Apple", "Mango",'???'];
fruits.copyWithin(2, 0);
// ["Banana", "Orange", "Banana", "Orange", "Apple"]

find (), findIndex () (return are only the first), fill (), keys () (index), values ​​() (both methods are equally applicable to an object), entries () Returns the key value traversal object - the Next key value is located and this is an array index value i.e. values ​​and array gap - the gap or empty automatically into undefined;

ES7

  ES6 change is really too much, version behind, relatively speaking, not so much, that is, it tends to be stable. 2016 release, ES7 mainly as follows:

  1. Array the Includes () method;
  2. ** exponentiation operator, equivalent to Math.pow ();
  3. Template string escape;

ES8

  2017 release:

1.async / await, then resolve nested too much promise ES6 front of the problem, of course, and there is no obvious pros and cons, just different writing and reading of async / await occur in pairs, example:

 1 async function myFetch() {
 2       let response = await fetch('coffee.jpg')
 3       return await response.blob()
 4 }
 5 
 6 myFetch().then((blob) => {
 7       let objectURL = URL.createObjectURL(blob)
 8       let image = document.createElement('img')
 9       image.src = objectURL
10       document.body.appendChild(image)
11 })

2.Object.values ​​(), the front has been introduced;

3.Object.entries (), the front has been introduced;

4.padStart () / padEnd (), to the extended string, the length parameter is the target to be used and the length of the string portion filled enough, such as the asterisk encrypted number as follows;

1 function encryStr(str, len, aimFlag = '*') {
2     const lastDigits = str.slice(-len)
3     const maskedNumber = lastDigits.padStart(str.length, aimFlag)
4     return maskedNumber
5 }

5. The end of the comma, ShareArrayBuffer (Google banned Firefox, security), Atomics, target (atomic ShareArrayBuffer object);

6.Object.getOwnPropertyDescriptors (), get the object attribute descriptors, such as a shallow copy:

1  // shallow copy of an object 
2  the Object.create (
 . 3    Object.getPrototypeOf (obj), 
 . 4    Object.getOwnPropertyDescriptors (obj) 
 . 5 )

ES9

  2018 release:

1.for await of, for of iteration with the generator, so that can traverse asynchronously, as an example, the definition of asyncGenerator omitted;

1 (async function() {
2       for await (num of asyncGenerator()) {
3             console.log(num)
4       }
5 })()

2. The template string escape part of grammar adjustment;

3. Reverse regular expression assertions, assertions defined: also known as non-expendable matching or non-matching access, it is a test of character before or after the current match position, it does not actually consume any characters, before is positive to assert. (?=pattern) Zero-width positive affirmation assert, (?!pattern) zero-width positive assertion negative, (?<=pattern) zero-width assertion reverse affirmative, (?<!pattern) zero-width reverse negative assertion;

4. Regular Unicode escape, s / dotAll mode, capture command group (individual back again summarized in detail);

5.Object Rest Spread, namely ... rest, before ES9, ... used for the operation of the array, such as the split to achieve replication, etc., in ES9 also extends to the object in this syntax, for example, to achieve the object replication , but a similar effect deep copy of the following examples,

 1 const input = {
 2   a: 1,
 3   b: 2,
 4   c: 4
 5 }
 6 const output = {
 7   ...input,
 8   c: 3
 9 }
10 input.a=0
11 console.log(input,output) // {a: 0, b: 2, c:4} {a: 1, b: 2, c: 3}

It is noted that, if the object is a property of an object, the object is copied shallow, deep copy may be understood as one layer only, in conjunction with the following examples of rest;

1 const input = {
2   a: 1,
3   b: 2,
4   c: 3
5 }
6 let { a, ...rest } = input
7 console.log(a, rest) // 1 {b: 2, c: 3}

6.Promise.prototype.finally (), regardless of the success or failure of Promise will perform the content here;

ES10

1.Array.prototype.flat () / flatMap (), flat depth is specified by the parameter dimensionality reduction, flatMap () and the map () method of the flat 1 and a depth () similar results may be substituted reduce () and concat (), the following example;

1 var arr1 = [1, 2, 3, 4]
2 arr1.flatMap(x => [[x * 2]]) // [[2], [4], [6], [8]]
3 arr1.flatMap(x => [x, x * 2]) // [1, 2, 2, 4, 3, 6, 4, 8]
4 arr.reduce((acc, x) => acc.concat([x, x * 2]), []) // [1, 2, 2, 4, 3, 6, 4, 8]

2.String.prototype.trimStart () / trimLeft () / trimEnd () / trimRight (), remove unilateral space, start / end is the standard name, left / right is an alias;

3.Object.fromEntries (), Object.fromEntries ([[ 'a', 1]]) // { 'a': 1}, is Object.entries () of the inverse function, the argument is a two-dimensional array of the form the map objects;

4.Symbol.prototype.description, Symbol object is a descriptor, read-only, in fact, it is the character of the new parameters of its time;

5.String.prototype.matchAll, reference match, well understood, canonical match;

6.Function.prototype.toString () return comments and spaces;

The parameters 7.try-catch catch non-essential can be directly try {} catch {} a;

8.BigInt, built-in objects, represents an integer greater than 2 53 -1 power, i.e., beyond the maximum number of integer Number, can be added to the definition of a large integer and n represents an integer literal behind, or with the BigInt (Integer Literals ) expressed the concern is not BigInt and other types of numerical calculation carried out, otherwise it will throw an exception, after BigInt out, JS primitive types will be increased to seven, as follows: • Boolean • Null • Undefined • Number • String • Symbol (ES6) • BigInt (ES10);

9.globalThis, this value of the global object;

10.import (), the introduction of dynamic, can take the then;

11. The private elements and methods, the keyword is #, private showing, as an example;

 1 class Counter extends HTMLElement {
 2       #xValue = 0
 3 
 4       get #x() { 
 5           return #xValue
 6       }
 7       set #x(value) {
 8             this.#xValue = value
 9             window.requestAnimationFrame(this.#render.bind(this))
10       }
11 
12       #clicked() {
13             this.#x++
14       }
15 
16       constructor() {
17             super();
18             this.onclick = this.#clicked.bind(this)
19       }
20 
21       connectedCallback() { 
22               this.#render()
23       }
24 
25       #render() {
26             this.textContent = this.#x.toString()
27       }
28 }
29 window.customElements.define('num-counter', Counter)

Spread

In addition, several of our usual enhance code efficiency characteristics useful:

1. Optional chain operator

  For example, when we usually request interface, a data processing interface may be relatively simple, there might be a nested data object, we have to take the data when relatively deep, have determined layer by layer in order to avoid the outer layer is null result in throwing an exception, as after let nestedProp = obj && obj.first && obj.first.second , With this feature, you can directly abbreviated to let nestedProp = obj? .first? .second , using a question mark instead of the original repeat partial write;

2. Merge operator vacancy

  For example, when we usually do || ternary operator to use or value, since 0, false air, and are treated as false, which will take the value of the back, and if you want to make these values ​​as a valid entry, then it to change the determination if compared lengthy, it can now be implemented directly ?? i.e. two question mark represents a valid null and undefined addition, as let c = a ?? b;

3.static keyword

  Similar to the static java, represents a static field, may also be used in conjunction with private #;

4.await extension

  ES8 await new / async only allows await use in async function, can now be used outside, such as const strings = await import ( `/ i18n / $ {navigator.language}`), as well as in the database http request or aspects are also easily connected;

The weak references WeakRef

  And WeakMap, WeakSet similar, both to achieve some weak reference, weakref weak reference is a real, weakref instance having a DEREF method, which returns the original object being referenced, if the original object has been collected, undefined object is returned .

More than a few extended attributes there is no widespread support for the use of caution.

Guess you like

Origin www.cnblogs.com/ljwsyt/p/12092667.html