Author: StevenLikeWatermelon

Juejin. Cn/post / 684490…

Recently, I have been reviewing ES6. In view of the new knowledge points of ES6, I have compiled a comprehensive knowledge and questions in the form of questions and answers.

What is ES6, why should I learn it, and what would happen if I didn’t?

Answer: ES6 is a new generation of JS language standard. It has upgraded and optimized the core content of JS language, standardized the JS use standard, and added the JS native method, making the USE of JS more standardized, more elegant, and more suitable for the development of large-scale applications. Learning ES6 is the only way to become a professional front end regular army. You can code and fight devils without learning ES6, but you can only be a guerrilla leader.

Q2: What are the differences between ES5, ES6 and ES2015?

A: ES2015 specifically refers to the next-generation JS language standard released in 2015. ES6 generally refers to the next-generation JS language standard, including ES2015, ES2016, ES2017, and ES2018. At present, ES2015 is equivalent to ES6 by default in most scenarios. ES5 generally refers to the language standard of the previous generation. ES2015 can be understood as the time dividing line between ES5 and ES6.

Q: What is a Babel and what does it do?

A: Babel is an ES6 transcoder that converts ES6 code into ES5 code for compatibility with platforms that do not yet support ES6.

Q: What is the use of let? Why use let when var is available?

Answer: before ES6, declaring variables can only use var, var declarations of variables is actually a very unreasonable way, accurately, because inside the ES5 not block-level scope is not reasonable, and even can be said to be a language level bugs (this is also a lot of c + +, Java developers don’t understand, also look down on JS language one of the disadvantages of). The lack of block-level scope brings with it a number of problems that are difficult to understand, such as for loop var leakage, variable overwriting, and so on. Let declared variables have their own block-level scope and fixed variable promotion with var declarations.

Q: What are some common ES6 upgrades and optimizations for String?

A:

1. Optimization:

ES6 adds a new string template that uses a backslash (‘) instead of adding strings when concatenating large chunks of string. It preserves all whitespace and newlines, making concatenation more intuitive and elegant.

2. Upgrade part:

ES6 adds an includes() method to the String stereotype, replacing the traditional indexOf method (indexOf -1 means no included characters). In addition, startsWith(), endsWith(), padStart(),padEnd(),repeat() and other methods are added to make it easier to find and complete strings.

Q: What are some common ES6 upgrades and optimizations for Array types?

A:

1. Optimization:

A. Array destruct assignment. ES6 can directly assign variables in the form of let [a,b,c] = [1,2,3]. When many variables are declared, there is no need to write many lets (var). In addition, the mapping relationship is clear, and default values can be assigned.

B. Extension operators. Extended operator (…) added in ES6 (important), can easily implement the array and loose sequence conversion, can replace the arguments object and apply method, easy to obtain the parameter set in case of unknown number of arguments. (Especially in ES5, Arguments is not a true array, but an array-like object, but the inversion of the extension operator can return a true array.) Let a = [2,3,4]; let a = [2,3,4]; Let b = […a])

2. Upgrade part:

ES6 adds find() to the Array prototype, replacing the traditional method of finding items containing an Array only with indexOf, and fixes the bug that indexOf cannot find NaN ([NaN].indexof (NaN) === -1). In addition, copyWithin(), includes(), fill(),flat() and other methods are added to facilitate string lookup, completion, and conversion.

Q: What are some common ES6 upgrades to the Number type?

A:

1. Optimization:

ES6 adds the isFinite(), isNaN() methods to the Number prototype to replace the traditional global isFinite(), isNaN() methods to check whether the Number isFinite or NaN. ES5’s isFinite() and isNaN() methods all convert non-numeric arguments to Number before judging them. This is unreasonable and causes the most strange behavior of isNaN(‘NaN’) === true –‘NaN’ is a string, But isNaN says this isNaN. Number.isnan () and number.isnan () do not have this problem (number.isnan (‘NaN’) === false). (isFinite())

2. Upgrade part:

In ES6, math.cbrt (), Trunc (), hypot() and other scientific enumeration methods are added to Math objects, which can be used to perform more comprehensive scientific calculations such as cube root and sum cube root.

Q: What are some common ES6 upgrades for Object types? (important)

A:

1. Optimization:

A. Object property variable declaration. ES6 can directly declare object properties or methods as variables. It is more concise, convenient and semantic than the traditional key-value pair declaration.

let [apple, orange] = ['red appe', 'yellow orange']; let myFruits = {apple, orange}; // let myFruits = {apple: 'red appe', orange: 'yellow orange'};Copy the code

The benefits of this approach are most evident when an object is destructed to an assignment (see optimization b.) or when a module outputs variables:

let {keys, values, entries} = Object; let MyOwnMethods = {keys, values, entries}; // let MyOwnMethods = {keys: keys, values: values, entries: entries}Copy the code

As you can see, the property variable declaration looks a little more concise. The method can also be written succinct:

let es5Fun = {    method: function(){}}; let es6Fun = {    method(){}}
Copy the code

B. Deconstruction assignment of objects. ES6 objects can also be destructively assigned to variables in the same way that arrays are destructively assigned:

let {apple, orange} = {apple: 'red appe', orange: 'yellow orange'};
Copy the code

C. Extension operators for objects (…) . The use of the extension operator for ES6 objects is not fundamentally different from the use of the array extension operator, since arrays are, after all, special objects. One of the most common and useful uses of the object extension operator is that it is easy to merge and decompose objects by fetching all or part of the traversable properties inside a target object.

let {apple, orange, ... otherFruits} = {apple: 'red apple', orange: 'yellow orange', grape: 'purple grape', peach: 'sweet peach'}; // otherFruits {grape: 'purple grape', peach: 'sweet peach'} The extension operator of an object is used when deconstructing an assignment. The extension operator can only be used for the last parameter (no more than otherFruits). Let moreFruits = {ripe: 'nice ripe '}; let allFruits = {apple, orange, ... otherFruits, ... moreFruits};Copy the code

D. Super. ES6 adds a super keyword like this to the Class Class. Unlike this, which always points to the object where the current function resides, the super keyword always points to the prototype of the object where the current function resides.

2. Upgrade part:

A. ES6 adds the is() method to the Object prototype to complete the ‘===’ method by comparing two target objects for equality. Object.is fixes a bug where NaN === NaN //false in the ‘=== =’ method is not valid. (Object.is(NaN, NaN) // true)

B. ES6 adds the assign() method to the Object stereotype, which can be used to add properties to the Object or to merge multiple objects.

const target = { a: 1 }; const source1 = { b: 2 }; const source2 = { c: 3 }; Object.assign(target, source1, source2); target // {a:1, b:2, c:3}Copy the code

Note: Assign target merges only its own attributes from source1 and source2, does not merge inherited attributes from source1 and source2, does not merge non-enumerable attributes from source1 and source2, and does not properly copy get and set attributes. Take the value of return).

C. ES6 added on the Object prototype getOwnPropertyDescriptors () method, this method enhances the ES5 getOwnPropertyDescriptor in () method, which can obtain the specified Object all its attributes describe objects. With the defineProperties() method, you can perfectly copy objects, including get and set properties.

D. ES6 adds getPrototypeOf() and setPrototypeOf() methods to get or set the prototype Object for the current Object. In ES5, the __proto__ attribute is not explicitly specified in the ES specification, but is added by the browser manufacturers, but is used by default because of its wide range of applications. This is not always possible in non-browser environments, so to be safe, use ES6’s new standard usage when getting or setting the prototype object for the current object.

E. ES6 also added methods object.keys (), object.values (), and object.entries () to the Object stereotype to get all the keys, values, and arrays of key-value pairs of an Object.

Q: What are some common ES6 upgrades and optimizations for Function types? (important)

A:

1. Optimization:

A. Arrow function **(core)**. The arrow function is one of the core upgrades of ES6. The arrow function does not have its own this, which changes the most difficult to understand this mechanism in JS functions in the past. Main optimization points:

I. This in the arrow function refers to the object where the function was defined, not where the function was executed. This in ES5 functions always refers to the object in which the function is executed. This makes it difficult to understand what this refers to in many cases, especially in non-strict mode, where this sometimes refers to global objects. This can even be attributed to one of the language level bugs. The arrow function in ES6 is optimized for this because it does not have its own this inside, which causes this to always point to the previous level of this. If the previous level is still an arrow function, it will continue pointing up until it points to the function that has its own this as its own this.

The arrow function cannot be used as a constructor because it does not have its own this and cannot be instantiated.

There is no argument object in the arrow function because the arrow function does not have its own this. (Can be replaced with the extension operator)

B. Default function assignment. Prior to ES6, function parameters could not be given default values and could only be implemented within the function by workarounds. ES6 does default function assignment in a more concise and explicit way.

function es6Fuc (x, y = 'default') { console.log(x, y); }es6Fuc(4) // 4, defaultCopy the code

2. Upgrade part:

ES6 adds a double colon operator to replace bind, call, and apply. (Browsers do not support transcoding, Babel already supports transcoding)

foo::bar; // equivalent to bar.bind(foo); foo::bar(... arguments); // equivalent to bar.apply(foo, arguments); Copy the codeCopy the code

Q: What is the Symbol for?

A: Symbol is the seventh primitive data type introduced in ES6. All Symbol() generates unique values, which can fundamentally solve the problem of overwriting attribute names due to too many Object attributes. The Symbol() attribute in an object cannot be used for… In traversal, but not private.

11. Q: What is Set and what does it do?

A: Set is a new data structure introduced by ES6, similar to Array. The members of a Set instance are similar to the members of an Array item. The difference is that the members of a Set instance are unique and not repeated. This feature makes it easy to de-iterate arrays.

Q: What is Map and what does it do?

A: Map is a new data structure similar to Object introduced in ES6. Map can be understood as a superset of Object, breaking the traditional definition of objects in the form of key-value pairs. The key of an Object is no longer limited to strings, but can also be Object. You can describe the properties of an object more fully.

Q: What is Proxy and what is its function?

A: Proxy is a new constructor in ES6, which can be understood as a Proxy of JS language. It is used to change some default JS language behaviors, including intercepting the default get/set and other underlying methods, so that THE use of JS is more free and can meet the needs of developers to the greatest extent. For example, by intercepting the object’s GET /set methods, you can easily customize the key or value you want. As you can see in the following example, you can define any key of myOwnObj to be the function you want.

Function createMyOwnObj() { Or Promise, or anything return new Proxy({}, {get(target, propKey, receiver) {return new Promise((resolve, Reject) => {setTimeout(() => {let randomBoolean = Math.random() > 0.5; let Message; If (randomBoolean) {Message = 'your ${propKey} got lucky'; resolve(Message); } else {Message = 'your ${propKey} failed'; reject(Message); }}, 1000); }); }}); }let myOwnObj = createMyOwnObj(); Myownobj.hahaha. Then (result => {console.log(result) // Your hahaha is lucky, }).catch(error => {console.log(error) // Your hahaha is not lucky, }) myownobj.wuwu.then (result => {console.log(result) // Your wuwuwu lucky, }).catch(error => {console.log(error) // Your wuwuwu failed}).catch(error => {console.log(error) //Copy the code

Q: Reflect, what does that mean?

A: Reflect is a new Object introduced in ES6. Reflect is a new Object introduced in ES6. It has two main functions: one is to integrate native methods (apply, delete, get, set, etc.) scattered in Object, Function, or global functions into Reflect. This makes it easier and more unified to manage some native apis. Second, Proxy can override the default native API, and Reflect can also backup the native API, so that even if the native API is overwritten, the default API can be used in the overwritten API.

15. Q: What is a Promise and what does it do?

A: Promise is a new object introduced in ES6, and its main purpose is to solve the “callback hell” caused by the JS asynchronous callback mechanism. It’s not a breakthrough API, but it encapsulates the asynchronous callback form, making it more elegant to write, more readable, and can be chained.

Appendix: 15 ES6 Promise practical practice questions

Q: What is an Iterator and what does it do? (important)

A: Iterator is an important concept in ES6. It is not an object or any data type. ES6 adds a Set and Map type, which is similar to the Array and Object types. Array and Object are traversable, but neither Set nor Map can be traversed using a for loop. There are two ways to solve this problem. The other is to add a unified traversal API for sets, Maps, arrays, and Objects. Obviously, the second is better, so ES6 naturally needs a design standard to unify traversal for all traversable types. Iterator is one such standard. Or a normative idea.

Just as JavaScript is a concrete implementation of the ECMAScript standard, the concrete implementation of the Iterator standard is the Iterator Iterator. The Iterator standard specifies that all values of [Symbol. Iterator] that are deployed with key values of [Symbol. This function must return an object that contains the next method and that executes next() to return an Iterator that contains the value/done property. These are called traversable objects. The Iterator returned after next() is also called the Iterator traversator.

//obj is traversable because it complies with the Iterator standard and contains the [Symbol. Iterator] method whose function conforms to the standard Iterator interface specification. Let Symbol. Iterator = {data: ['hello', 'world'], [Symbol. let index = 0; return { next() { if (index < self.data.length) { return { value: self.data[index++], done: false }; } else { return { value: undefined, done: true }; }}}; }};Copy the code

The [Symbol. Iterator] method for Set, Map, Array, and String conforms to the standard iterator interface. So Set, Map, Array, and String are traversable by default.

//Arraylet array = ['red', 'green', 'blue']; Array [Symbol. Iterator]().next() //{value: "red", done: false}//Stringlet string = '1122334455'; String [Symbol. Iterator]().next() //{value: "1", done: false}//setlet set = new Set(['red', 'green', 'blue']); Set [Symbol. Iterator]().next() //{value: "red", done: false}//Maplet map = new map (); let obj= {map: 'map'}; map.set(obj, 'mapValue'); map[Symbol.iterator]().next() {value: Array(2), done: false}Copy the code

Q: For… In and for… What’s the difference between “of”?

A: If you see question 16, it’s easy to answer. Question 16 mentions that ES6 has unified traversable standards and defined traversable objects, so what method is used to traverse? The answer is to use for… Of. ES6 specifies that objects (traversable objects) that are deployed with the Iterator interface can be passed through the for… Of to traverse, while for.. In can only traverse objects.

This means that arrays can also be used for… Of traversal, which greatly facilitates array values and avoids many programs using for.. Go through the bad habits of the group.

The extension operator mentioned above is essentially a for.. An implementation of the of loop.

What is a Generator function and what does it do?

A: If JavaScript is a concrete implementation of the ECMAScript standard and an Iterator Iterator is a concrete implementation of Iterator, then Generator functions can be said to be a concrete implementation of the Iterator interface.

Executing a Generator function returns a iterator object. Each yield in the Generator function is the same as the yield in the next() method of the iterator object, and you can change the behavior of the Generator function by passing in a custom value through the next(value) method.

Generator functions make asynchronous programming and control flow management easier and more elegant when combined with Thunk functions.

19, async function is what, what function?

A: The async function can be understood as a Generator function syntax sugar for the built-in autoexecutor. It works with THE Promise of ES6 for a near-perfect asynchronous programming solution.

Appendix: Minimalist implementation of handwritten async await (20 lines done)! An Interview with Apribyte is a must

What is Class extends?

A: ES6’s class can be thought of as just syntactic sugar for an ES5 constructor that generates instance objects. It refers to the Java language, defines the concept of a class, makes the object prototype writing more clear, object instantiation is more like object-oriented programming. Class can be inherited through the extends implementation. How it differs from the ES5 constructor:

A. All methods defined internally by a class are non-enumerable.

///ES5function ES5Fun (x, y) { this.x = x; this.y = y; }ES5Fun.prototype.toString = function () { return '(' + this.x + ', ' + this.y + ')'; }var p = new ES5Fun(1, 3); p.toString(); Object.keys(ES5Fun.prototype); //['toString']//ES6class ES6Fun { constructor (x, y) { this.x = x; this.y = y; } toString () { return '(' + this.x + ', ' + this.y + ')'; }}Object.keys(ES6Fun.prototype); / / []Copy the code

The class of B.ES6 must be operated with the new command, while the constructor of ES5 can be executed without new.

C. Es6’s class class has no variable promotion and must be defined before it can be instantiated, unlike ES5 where constructors can be written after the instantiation.

D. es5 inherits by creating an instance object of the subclass this, and then adding methods from the superclass to this. In ES6, the inheritance mechanism is completely different. In ES6, the properties and methods of the parent instance object are added to this (so the super method must be called first), and then the constructor of the subclass is used to modify this.

21, Module, export, import is what, what is the role?

A: Module, export, and import are the design ideas and implementation solutions used by ES6 to unify the front-end modular solution. The appearance of Export and Import unified the implementation scheme of front-end modularization, integrated and standardized the browser/server modularization method, used to replace the traditional AMD/CMD, requireJS, seaJS, commondJS and a series of different implementation schemes of front-end modules, so that the front-end modularization is more unified and standardized. JS can also be more capable of large-scale application development.

Import imports modules that are loaded statically (at compile time) rather than dynamically (at run time).

Import Export The value of the exported interface is a dynamic binding relationship. That is, the real-time value of the module can be obtained through this interface.

Xxii. In daily front-end code development, what programming optimizations or specifications are worth using ES6 to improve?

A:

  1. The arrow function is used insteadvar self = this;In the practice.
  2. Let is often used instead of the var command.
  3. Frequently used array/object structure assignment to name variables, structure is more clear, semantic clarity, better readability.
  4. In the case of long string multi-variable combination, using template string instead of string accumulation can achieve better results and reading experience.
  5. To generate instantiated objects, replace the traditional constructor with the Class Class.
  6. In large-scale application development, we should keep module modular development thinking, distinguish the relationship between modules, and often use import and export methods.

Statement: the copyright of the article belongs to the author, if there is infringement, please contact xiaobian to delete.

Recommended reading: **
* [Gitlab - ci: from the front end of the automated deployment] (HTTP: / / http://mp.weixin.qq.com/s?__biz=MzIyMDkwODczNw==&mid=2247500080&idx=1&sn=6d43b95096bb5025cf34ee 93bb439261&chksm=97c65c9ea0b1d5888e131dad0a6ccdf82034d8e81050ebbcbbfbf7c522d68e77da20429fb1df&scene=21#wechat_redirect) * [article, understand the realization of the single sign-on (sso) three of the following ways] (HTTP: / / http://mp.weixin.qq.com/s?__biz=MzIyMDkwODczNw==&mid=2247498639&idx=1&sn=1386ea609c31345e380f21f12cb 4dc05&chksm=97c66621a0b1ef3777f00e35035e4b097404f64bc39b17fbb225b2fee9ec3eab7be2d4e5863c&scene=21#wechat_redirect) * [14 front-end common rich text editor plug-in] (HTTP: / / http://mp.weixin.qq.com/s?__biz=MzIyMDkwODczNw==&mid=2247499701&idx=1&sn=a7f8ac774bcf324456079948fd09 f27a&chksm=97c6621ba0b1eb0d0fce2ad8b7d445aff2da18f8d04e5bd5e68d549cde2d3d62421d6773fde6&scene=21#wechat_redirect) * [Finally, someone has clarified Nginx.] (http://mp.weixin.qq.com/s?__biz=MzIyMDkwODczNw==&mid=2247498339&idx=1&sn=6c42ff6f859d3e02c360e56b585d9816&chksm=97c667c Da0b1eedbb665a83f66f8c264a257763b77a03e00c87d0d1d8373c0c1ef3b65c3b193 & scene = 21 # wechat_redirect) * [recommendation 130 makes you shine at the moment of the website, There is always a need it to be] (HTTP: / / http://mp.weixin.qq.com/s?__biz=MzIyMDkwODczNw==&mid=2247498262&idx=1&sn=886534663bb8209d4d9ad32232eb3d5d&chksm = 97 c667b8a0b1eeaea90f83e91505d40efd4c606aca7e1f8061697f569bc91f8dba3497bc7a85 & scene = 21 # wechat_redirect) * [covering 33 Vue 99% One of the interview] (HTTP: / / http://mp.weixin.qq.com/s?__biz=MzIyMDkwODczNw==&mid=2247498262&idx=2&sn=bc792931ee337d3e7cb73bdb8fa4599e&chksm =97c667b8a0b1eeae0915411943ab1d50ca0f4847882d56020d23b4b9308021af8326e1ffb631&scene=21#wechat_redirect)