Front-end framework learning - ES6 new features (Shang Silicon Valley web notes)

ECMASriptIt is a scripting programming language standardized by Ecma International through ECMA-262. javaScript is also an implementation of this specification.

Source of notes: station b

Shang Silicon Valley Web front-end ES6 tutorial, covering ES6-ES11
Mr. Ruan Yifeng: Introduction to ECMAScript 6

ES6

let keyword

The characteristics of variables declared using the let keyword:

  1. No repetition allowed
  2. block-level scope
  3. variable hoisting does not exist
  4. does not affect the scope chain
const keyword

The const keyword is used to declare constants. The const declaration consists of the following characteristics

  1. declaration must assign an initial value
  2. Identifiers are generally uppercase
  3. Duplicate statement not allowed
  4. Value does not allow modification
  5. block scope
Variable Destructuring Assignment

ES6 allows extracting values ​​from arrays and objects and assigning values ​​to variables according to a certain pattern

	 //数组的解构赋值
	const arr = ['张学友', '刘德华', '黎明', '郭富城'];
	let [zhang, liu, li, guo] = arr;
	//对象的解构赋值
	const lin = {
    
    
	 name: '林志颖',
	 tags: ['车手', '歌手', '小旋风', '演员']
	};
	let {
    
    name, tags} = lin;
template string

The template string (template string) is an enhanced version of the string, identified by backticks (`), features:

  1. Newline characters can appear in the string
  2. Variables can be output in the form of ${xxx}
	// 定义字符串
	let str = `<ul>
	 <li>沈腾</li>
	 <li>玛丽</li>
	 <li>魏翔</li>
	 <li>艾伦</li>
	 </ul>`;
	// 变量拼接
	let star = '王宁';
	let result = `${
      
      star}在前几年离开了开心麻花`;
Simplified object writing

ES6 allows variables and functions to be written directly inside curly braces as properties and methods of objects. Such
writing is more concise.

let name = '尚硅谷';
let slogon = '永远追求行业更高标准';
let improve = function () {
    
    
 console.log('可以提高你的技能');
}
//属性和方法简写
let atguigu = {
    
    
	 name,// 属性名和变量名相同可以简写
	 slogon,// 属性名和变量名相同可以简写
	 improve,// 属性名和函数变量名相同可以简写
	 change() {
    
    // change:function(){}的简写方式
	 	console.log('可以改变你')
	 }
};
arrow function

ES6 allows the use of "arrows" (=>) to define functions.

// 1. 通用写法
let fn = (arg1, arg2, arg3) => {
    
    
	return arg1 + arg2 + arg3;
}
// 2. 省略小括号的情况,只有一个参数
let fn2 = num => {
    
    
	return num * 10;
};
// 3. 省略花括号,省略花括号的同时要省略`return`
let fn3 = score => score * 20;
// 4. this指向2声明所在作用域中this的值
let fn4 = () => {
    
    
	console.log(this);//Windows
}
let school = {
    
    
	 name: '尚硅谷',
	 getName(){
    
    
	 	let fn5 = () => {
    
    
	 		console.log(this);// this指向school
	 	}
	 	fn5();
	 }
};

The arrow function does not change the point of this, so it is very suitable for specifying the callback function

rest parameters

ES6 introduces the rest parameter, which is used to obtain the actual parameters of the function and is used instead of arguments

// 类似java中的可变参数
function add(...args){
    
    
 	console.log(args);
}
add(1,2,3,4,5);
// rest参数必须是最后一个形参,在其他参数都确定之后才是rest参数
function minus(a,b,...args){
    
    
	console.log(a,b,args);
}
minus(100,1,2,3,4,5,19);
spread spread operator

The spread operator (spread) is also three dots (…). It is like the inverse operation of the rest parameter, converting an array into a sequence of parameters separated by commas, and unpacking the array. Objects can also be extended after ES9

// 展开数组
let tfboys = ['德玛西亚之力','德玛西亚之翼','德玛西亚皇子'];
function fn(){
    
    
	console.log(arguments);// 输出不是数组对象而是,'德玛西亚之力', '德玛西亚之翼', '德玛西亚皇子'
}
fn(...tfboys)
// 展开对象
/**
* 展开对象
*/
let skillOne = {
    
     q: '致命打击',};
let skillTwo = {
    
     w: '勇气'};
let skillThree = {
    
     e: '审判'};
let skillFour = {
    
     r: '德玛西亚正义'};
let gailun = {
    
    ...skillOne, ...skillTwo,...skillThree,...skillFour};
Promise

Promises are a new solution to asynchronous programming introduced by ES6. Syntactically Promise is a constructor
that encapsulates an asynchronous operation and can get its success or failure result.

	//实例化 Promise 对象
    const p = new Promise(function(resolve, reject){
    
    
   		resolve(data);// 成功时使用这个方法
   		reject(err);// 失败时使用这个方法
    });

    //调用 promise 对象的 then 方法
    p.then(function(value){
    
    // then后面的第一个函数是成功的回调,第二个函数是失败时的回调
        console.log(value);
    }, function(reason){
    
    
        console.error(reason);
    })
    // 程序发生错误的时候调用
    p.catch(function(reason){
    
    
      console.warn(reason);
   });
Modular

Modularization refers to splitting a large program file into many small files, and then combining the small files.
benefit:

  1. prevent naming conflicts
  2. Improve code reuse
  3. Enhance maintainability, only need to adjust the corresponding module if there is a problem

The modular function mainly consists of two commands:

  • The export command is used to specify the external interface of the module
  • The import command is used to import functionality provided by other modules
// 在m1.js中导出
	// 分别暴露
	export let school = '尚硅谷';
	export function teach() {
    
    
	    console.log("我们可以教给你开发技能");
	}
	// 统一暴露
	export {
    
    school, teach};
	// 默认暴露
	export default {
    
    
	    school: 'ATGUIGU',
	    change: function(){
    
    
	        console.log("我们可以改变你!!");
	    }
	}
// 在app.js中使用
	import {
    
    school, teach} from "./src/js/m1.js";
	// 针对默认暴露可以这样写
	import m1 from "./src/js/m1.js";

ES8

async and await

The purpose of async and await is to simplify the use of api in promise. The combination of the two syntaxes can make asynchronous code the same as synchronous code.
Solving the callback hell problem

async function

The return value of the async function is a promise object.
The result of the promise object is determined by the return value of the async function execution.

await function

  1. await must be written in an async function
  2. The expression on the right side of await is generally a promise object
  3. await returns the value of promise success
  4. If the promise of await fails, an exception will be thrown, which needs to be captured and processed by try...catch
async function main() {
    
    
     try {
    
    
         let result = await p;
         console.log(result);
     } catch (e) {
    
    
         console.log(e);
     }
 }

ES9

Rest/Spread properties

Rest parameters and spread extension operators have been introduced in ES6, but ES6 is only for arrays, and
ES9 provides array-like rest parameters and extension operators for objects

function connect({
     
     host, port, ...user}) {
    
    
	console.log(host);
	console.log(port);
	console.log(user);// 可以直接将后三个参数封装到user中
}
connect({
    
    
	host: '127.0.0.1',
	port: 3306,
	username: 'root',
 	password: 'root',
	type: 'master'
});

Guess you like

Origin blog.csdn.net/u013795102/article/details/132355498