The following editor will bring you an incomplete guide (share) on changing JavaScript code to ES6 syntax. The editor thinks it’s pretty good, and now I want to give it to you and give it as a reference. Let’s follow the editor and take a look
Table of Contents
##
* 核心例子 * 修改成静态变量(const)或块级变量(let) * 开始修改 * 疑问解释(重复定义会发生什么) * 疑问解释(let的块级作用域是怎样的) * 疑问解释(const定义的变量在基础数据类型和引用类型中的差异) * 修改成Promise的形式 * 预备知识(回调函数是什么) * 预备知识(如何把回调函数改为Promise) * 开始修改 * 修改成箭头函数(Arrow Function) * 预备知识(箭头函数是什么) * 预备知识(箭头函数函数中的this是个坑) * 开始修改 * 修改拼接字符串成模板字符串 * 预备知识(字符串的拼接方式) * 预备知识(改为模板字符串的方式) * 开始修改 * 修改成解构的对象 * 修改成Class
Core Example
For the examples in this article, please test in the latest Chrome. Configuring the environment for converting ES6 to ES5 is beyond the scope of this article.// 定义一个学生构造函数 var People = function(name, age) { this.name = name this.age = age } // 创建小明实例 var xiaoming = new People('xiaoming', 18) // 定义一个考试函数 // 定义两个回调函数,在适当的时候把参数传进去 var 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) } } // 开始考试 // 传入的两个回调函数分别处理结果 examStart(function(res) { console.log(res) }, function(res) { console.log(res) })
Modify it into a static variable (const) or block-level variable (let)
When the value of your variable needs to be modified When doing so, block-level variables (let) should be used. Other times, use static variables (const). Whether it is 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 use corresponding prototype methods to operate on the internal data.Start modifying
The variables we define here do not need to be modified, so directly change them all to const. In a project, there is a trick to determine whether to change it to const or let. You can use the variable check function of the editor (for example, in sublime, double-click the variable name and then ctrl+d). Then determine whether the variable has been assigned a value in the code, and whether the variable needs to be modified based on your own judgment. If not, use const.// 修改一 var ==> const const Student1 = function(name, age) { this.name = name this.age = age } // 修改二 var ==> const const xiaoming1 = new Student1('xiaoming', 18) // 修改三 var ==> const const examStart1 = function(callbackSucc, callbackFail) { // 修改四 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) { console.log(res) }, function(res) { console.log(res) })
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
// let定义的变量存在块级作用域 if(true) { let test1 = 2333 } console.log(test1) // Uncaught ReferenceError: t is not defined // var定义的变量不存在,会直接成为全局变量 if(true) { var test2 = 2333 } console.log(test2) // 2333
// const定义的变量值是基础数据类型时,不能修改值,也不能修改类型 const num = 2333 num = 2334 // Uncaught TypeError: Assignment to constant variable. num = '' // Uncaught TypeError: Assignment to constant variable. // const定义的变量值是引用类型时,可以修改值 const obj = {} obj.test = 2333 console.log(obj.test) // 2333 const arr = [] arr.push(1) console.log(arr) // [1]
Modify it into the form of Promise
From an application perspective, the main function of Promise is to The callback function is changed to the chain call mode. When there are multiple nested callback functions, the code will have many indentation levels, which is not conducive to reading. This is when Promise comes on stage. If there is only one callback function and no error handling is involved, it is not recommended to change it to the form of Promise.Preliminary knowledge (what is a callback function)
The callback function refers to defining a function and the parameter passed in is a function. Then execute the passed-in function at a specific location in the function, and pass in the required data as parameters. Callback functions are common in asynchronous programming. Such as sending Ajax requests and asynchronous file operations in NodeJS. Seeing is better than hearing. Let’s take a look at the simplest example.// 定义一个支持传入回调函数的函数 function fun1(callback) { // 执行传入的函数,并将值2333作为参数传入 callback(2333) } // 执行定义的函数 fun1(function(res){ // 输出传入的参数 console.log(res) })
Preliminary knowledge (how to change the callback function to Promise)
This is just for example and does not involve error handling When , it is not recommended to change it to Promise.function fun2() { // 在函数中返回一个Promise对象 // resolve和reject都是函数 return new Promise(function(resolve, reject){ // resolve函数中的参数将会出现在.then方法中 // reject函数中的参数将会出现在.ctch方法中 resolve(2333) }) } fun2().then(function(res){ console.log(res) // 2333 })
Start modifying
Promise uses resolve and reject to put the correct result and error prompt in the chain call respectively In the .then and .catch methods.const examStart2 = function() { // 返回一个Promise对象 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) { console.log(res) }) .catch(function(err) { console.log(err) })
Modify it into an arrow function (Arrow Function)
Preliminary knowledge (what is an arrow function)
The arrow function is a small tool used to help us simplify the function structure.// 普通函数形式 const add1 = function(a, b) { return a + b } add1(1, 2) // 3 // 箭头函数形式 const add2 = (a, b) => a + b add2(1, 2) // 3
Preliminary knowledge (this in the arrow function function is a pit)
// 箭头函数没有独立的this作用域 const obj1 = { name: 'bw2', showName: () => { return this.name } } obj1.showName() // "" // 解决方案:改为function模式 const obj2 = { name: 'bw2', showName: function() { return this.name } } obj2.showName() // "bw2"
Start modifying
##
var examStart3 = function() { // 修改一 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) } }) } // 修改二 examStart3().then((res) => console.log(res)).catch((err) => console.log(err))
Preliminary knowledge (method of splicing strings)
const xh1 = 'xiaohong' console.log('I\'m ' + xh1 + '.') // I'm xiaohong.
The string template no longer uses single quotes, but the ` key (the one below ESC) in the English input state.
const xh2 = 'xiaohong' console.log(`I'm ${xh2}.`) // I'm xiaohong.
var examStart4 = function() { 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}`) } }) } examStart4().then((res) => console.log(res)).catch((err) => console.log(err))
Object destructuring is often used when NodeJS imports a module in a package. For objects written by yourself, if you need to deconstruct them, you must ensure that the names in the objects are deconstructed without causing conflicts. This is for the convenience of examples, and no very unique naming is used.
const People2 = function(name, age) { this.name = name this.age = age } const xiaoming2 = new People2('xiaoming2', 18) // 开始结构 const {name, age} = xiaoming2 // 现在可以独立访问了 console.log(name) // xiaoming2 console.log(age) // 18
The class is a syntax sugar, but this does not prevent us from eating it.
In React, the definition of a template is usually a class, and the life cycle methods are also written in the class.
class People3 { constructor(name, age){ this.name = name this.age = age } showName() { return this.name } } const xiaoming3 = new People3('xiaoming3', 18) console.log(xiaoming3) // People {name: "xiaoming3", age: 18} console.log(xiaoming3.showName()) // xiaoming3
The above is the detailed content of Teach you how to change JavaScript code to ES6 syntax guide. For more information, please follow other related articles on the PHP Chinese website!