Table of contents
* Core Examples * Modify to static variable(const)or block-level variable(let) * Start modifying * Question explanation(What happens if you repeat the definition) * Question explanation(letWhat is the block-level scope of) * Question explanation(constDifferences in the underlying data type and reference type of the defined variable) * Modify toPromiseForm of * Preparation knowledge(What is a callback function) * Preparation knowledge(How to change the callback function toPromise) * Start modifying * Modify to箭头函数(Arrow Function) * Preparation knowledge(What is the arrow function) * Preparation knowledge(Arrow function functionthisIt's a pit) * Start modifying * Modify the splicing string into template string * Preparation knowledge(String stitching method) * Preparation knowledge(How to change to template string) * Start modifying * Modify to解构的对象 * Modify toClass
Core Examples
For examples in the article, please test them in the latest Chrome. The environment for configuring ES6 to ES5 is not within the scope of this article.
// Define a student constructorvar People = function(name, age) { = name = age } // Create a Xiaoming instancevar xiaoming = new People('xiaoming', 18) // Define an exam function// Define two callback functions and pass parameters in at the appropriate timevar examStart = function(callbackSucc, callbackFail) { var result = prompt('1+5=') if(result === '6') { callbackSucc('Awesome. Your answer is ' + result) } else { callbackFail('You can try again. Your answer is ' + result) } } // Start the exam// The two incoming callback functions process the results separatelyexamStart(function(res) { (res) }, function(res) { (res) })
Modify to a static variable (const) or block-level variable (let)
When the value of your variable needs to be modified, you should use block-level variables (lets). Other times, static variables (const) are used.
Neither a static variable (const) or a block-level variable (let), it cannot be defined repeatedly, otherwise an error will be reported.
Once a static variable (const) is defined, the data type cannot be changed. However, reference types, such as Array and Object, can be operated internally by using corresponding prototype methods.
Start modifying
The variables we define here do not need to be modified, so they are all changed to const. In the project, there is a trick to determine whether to change to const or let, which can use the editor's variable check function (for example, in sublime, ctrl+d after double-clicking the variable name). Then determine whether this variable has been assigned in the code, and whether it is necessary to modify this variable according to your own judgment. If you do not need it, use const.
// Modify one var ==> constconst Student1 = function(name, age) { = name = age } // Modify two var ==> constconst xiaoming1 = new Student1('xiaoming', 18) // Modify three var ==> constconst examStart1 = function(callbackSucc, callbackFail) { // Modify four var ==> const const result = prompt('1+5=') if(result === '6') { callbackSucc('Awesome. Your answer is ' + result) } else { callbackFail('You can try again. Your answer is ' + result) } } examStart1(function(res) { (res) }, function(res) { (res) })
Question explanation (what happens if you repeat the definition)
const author = 'bw2' const author = 'bw3' // Uncaught SyntaxError: Identifier 'author' has already been declared let author = 'bw4' // Uncaught SyntaxError: Identifier 'author' has already been declared
Question explanation (What is the block-level scope of let)
//The variables defined by let exist in block-level scopeif(true) { let test1 = 2333 } (test1) // Uncaught ReferenceError: t is not defined // The variable defined by var does not exist and will directly become a global variableif(true) { var test2 = 2333 } (test2) // 2333
Question explanation (the difference between the underlying data type and reference type of variables defined by const)
Before starting the example, review the following basic data types. Number, String, Boolean, null, undefined, Symbol. Among them, Symbol is newly added from ES6. Except for the basic data type, all are reference types. Common reference types are Array and Object.
// When the variable value defined by const is the basic data type, the value cannot be modified, nor can the type be modified.const num = 2333 num = 2334 // Uncaught TypeError: Assignment to constant variable. num = '' // Uncaught TypeError: Assignment to constant variable. // When the variable value defined by const is a reference type, the value can be modifiedconst obj = {} = 2333 () // 2333 const arr = [] (1) (arr) // [1]
Modify to Promise
From an application perspective, the main function of Promise is to change the callback function to a chain call mode.
When there are multiple nested callback functions, the code will have many indentation levels, which is not conducive to reading. Promise will be on the stage at this time.
If there is only one callback function and does not involve error handling, it is not recommended to modify it to the form of Promise.
Preparation knowledge (what is the callback function)
A callback function refers to defining a function, and the passed parameter is a function. Then, at a specific location in the function, execute the passed function and pass the required data in as parameters. Callback functions are commonly used in asynchronous programming. For example, sending Ajax requests and asynchronous file operations in NodeJS. It is better to see it at first sight than to hear it. Let’s take a look at the simplest example.
// Define a function that supports incoming callback functionsfunction fun1(callback) { // Execute the passed function and pass the value 2333 as a parameter in callback(2333) } // Execute the defined functionfun1(function(res){ // Output incoming parameters (res) })
Preparation knowledge (how to change the callback function to Promise)
This is just for an example. When there is no error handling, it is not recommended to modify it to Promise.
function fun2() { // Return a Promise object in the function // Resolve and reject are both functions return new Promise(function(resolve, reject){ // The parameters in the resolve function will appear in the .then method // The parameters in the reject function will appear in the .ctch method resolve(2333) }) } fun2().then(function(res){ (res) // 2333 })
Start modifying
Promise uses resolve and reject to place the correct result and error prompts in the .then and .catch methods of chain call.
const examStart2 = function() { // Return a Promise object return new Promise(function(resolve, reject) { var result = prompt('1+5=') if(result === '6') { resolve('Awesome. Your answer is ' + result) } else { reject('You can try again. Your answer is ' + result) } }) } examStart2() .then(function(res) { (res) }) .catch(function(err) { (err) })
Modify to Arrow Function
Preparation knowledge (what is the arrow function)
The arrow function is a widget used to help us simplify the structure of the function.
// Ordinary function formconst add1 = function(a, b) { return a + b } add1(1, 2) // 3 // Arrow function formconst add2 = (a, b) => a + b add2(1, 2) // 3
Preparation knowledge (this in the arrow function function is a pit)
// Arrow function has no independent scope of thisconst obj1 = { name: 'bw2', showName: () => { return } } () // "" // Solution: Change to function modeconst obj2 = { name: 'bw2', showName: function() { return } } () // "bw2"
Start modifying
var examStart3 = function() { // Modify one return new Promise((resolve, reject) => { var result = prompt('1+5=') if(result === '6') { resolve('Awesome. Your answer is ' + result) } else { reject('You can try again. Your answer is ' + result) } }) } // Modify twoexamStart3().then((res) => (res)).catch((err) => (err))
Modify the splicing string into template string
Preparation knowledge (stitching method of strings)
const xh1 = 'xiaohong' ('I\'m ' + xh1 + '.') // I'm xiaohong.
Preparation knowledge (to change to template string)
The string template no longer uses single quotes, but is the ` key in English input state (the one below ESC).
const xh2 = 'xiaohong' (`I'm ${xh2}.`) // I'm xiaohong.
Start modifying
var examStart4 = function() { return new Promise((resolve, reject) => { var result = prompt('1+5=') if(result === '6') { // Modify one resolve(`Awesome. Your answer is ${result}`) } else { // Modify two reject(`You can try again. Your answer is ${result}`) } }) } examStart4().then((res) => (res)).catch((err) => (err))
Modify into a deconstructed object
Object destruction is often used when NodeJS imports a module in a package. For objects you write, if you need to deconstruct, you must ensure that the naming inside the object is deconstructed without causing conflicts. This is for the convenience of examples, and there is no unique naming.
const People2 = function(name, age) { = name = age } const xiaoming2 = new People2('xiaoming2', 18) // Start the structureconst {name, age} = xiaoming2 // Now available for independent access(name) // xiaoming2 (age) // 18
Modify to Class
Class is a syntactic sugar, but this does not prevent us from eating it.
In React, the definition of a template is usually a class, and the lifecycle method is also written in the class.
class People3 { constructor(name, age){ = name = age } showName() { return } } const xiaoming3 = new People3('xiaoming3', 18) (xiaoming3) // People {name: "xiaoming3", age: 18} (()) // xiaoming3
But addiction? The article is over. However, the exploration of ES6 will continue to save updates.
The above article is the incomplete guide to changing JavaScript code to ES6 syntax (sharing) is all the content I share with you. I hope you can give you a reference and I hope you can support me more.