[Front-end] ECMAScript6 from entry to advanced

[Front-end] ECMAScript6 from entry to advanced

1.ES6 introduction and environment construction

1.1. Introduction to ECMAScript 6

Insert image description here

(1) What is ECMAScript 6?

ECMAScript 6.0 (hereinafter referred to as ES6) is the next generation standard of the JavaScript language and was officially released in June 2015. Its goal is to enable the JavaScript language to be used to write complex large-scale applications and become an enterprise-level development language.

(2) The relationship between ECMAScript and JavaScript

ECMAScript is a standard for JavaScript, and JavaScript is an implementation of ECMAScript. In other words, if JavaScript is a language, then ECMAScript is the grammar book followed by this language.

(3) The relationship between ES6 and ECMAScript 2015

In 2011, ECMAScript version 5.1 was released, and the ECMA organization began to prepare version 6.0. But because this version introduces too many grammatical features, it is impossible to cover all features in one version. Therefore, the standards committee decided that the standard would be officially released in June every year as the official version of that year. In the following time, changes will be made based on this version. Until June of the next year, the draft will naturally become the new year's version. This way, the previous version number is not needed, just the year stamp.

In this way, the first version of ES6 was officially released in 2015.6, and its official name is "ECMAScript 2015 Standard" (ES2015 for short).

1.2.Babel tool to build ES6 environment

Code written in ECMAScript 2015+ syntax is converted to backward-compatible JavaScript syntax so that it can run in current and older browsers or other environments.

  • First make sure there is node in the environment
node安装:http://nodejs.cn/download/
  • Initialize project
// 使用默认配置初始化项目
npm init -y
  • Install the corresponding dependency packages
// 本地安装babel-cli及对应的转化规则
npm install --save-dev babel-cli babel-preset-es2015

// 阿里巴巴定制的镜像源
npm install -g cnpm --registry=https://registry.npm.taobao.org
  • Create project directory

    • The src directory is used to store the written es6 code

    • The dist directory is used to store code converted from es6

  • Configure babel

Create new .babelrcfile

// 配置用于转化当前代码的规则集
{
    
    
  "presets": ["es2015"]
}

Basic usage of babel

// -o 参数指定输出文件
node_modules/.bin/babel src/index.js -o dist/index.js

// -d 参数指定输出目录
node_modules/.bin/babel src -d dist

Configure package.json file for real-time compilation

// 配置启动脚本的命令
"scripts": {
    
    
  // 监听index.js文件,一发生变化就执行babel转译的命令
  "dev": "babel src -w -d dist",
}

2. New declaration and data assignment methods

2.1. Variable declaration let and const

Scope is the effective scope of a variable. Previously there were only global scope and function scope. Now there is a new block-level scope. There are two new variable declaration methods, let and const, in es6.

(1) The similarities between let and const

  • Only valid within the declared code block
if (true) {
    
    
  var a = "a";
}
console.log(a);
// let声明变量,const同理
if (true) {
    
    
  let b = "b";
}
console.log(b);

Insert image description here

  • Duplicate declarations are not allowed within the same scope

Insert image description here

  • Without variable promotion, a variable cannot be used before it is declared.
console.log(a);
var a = 'a';

console.log(b);
let b = '1';

Insert image description here

Variables declared with var will have the problem of variable promotion. If let or const is used, the problem of variable promotion will be eliminated. If an undefined variable is encountered, an error will be thrown directly.

(2) The difference between let and const

  • const is used to declare a read-only variable
const x = 10;
x = 13;
console.log(x);

Note: Variables declared as const must be assigned a value immediately. If a simple type of data is declared, the value of the variable cannot be changed.

Insert image description here

2.2.ES6 new data type Symbol

Before ES6, the primitive data types of JavaScript were Number, String, Boolean, Null, and Undefined. A new Symbol unique type was added in ES6.

The attribute names of objects are prone to naming conflicts. In order to ensure the uniqueness of key names, es6 introduces Symbol, a new primitive type of data, to ensure that each variable created is unique.

  • Symbol type data is a string-like data type.
  • Since the value returned by the Symbol function is primitive type data, not an object, the new command cannot be used before the Symbol function, otherwise an error will be reported.
let s = Symbol();
console.log(typeof s);

Insert image description here

let s1 = Symbol();
let s2 = Symbol();
console.log(s1===s2);

let l1 = Symbol('lixiang');
let l2 = Symbol('lixiang');
console.log(l1===l2);

Insert image description here

Define the unique property name of the object

// 在对象里用Symbol作为属性名的三种写法
let s = Symbol();

// 第一种方式: 借助数组读取s变量,此时不能用点运算符,点运算符默认后面的参数是字符串
let a = {
    
    };
a[s] = 'lixiang'

// 第二种方式: 构造时声明
let a = {
    
    
  [s]: 'lixiang'
}

// 第三种 Object.defineProperty
let a = {
    
    };
Object.defineProperty(a, s, {
    
     value: 'lixiang' });

Insert image description here

Define constants

const s = Symbol("李祥");

Insert image description here

2.3. Detailed explanation of destructuring assignment

(1) What is destructuring assignment?

Destructuring assignment can be understood as syntactic sugar for assignment operations. It performs pattern matching on an array or object, and then assigns values ​​to the variables in it. The code is written concisely, with clear semantics, and it also facilitates the reading operation of the object array.

In ES6, as long as some kind of data can be looped and iterated, destructuring and assignment can be performed.

(2) Array destructuring

// 变量多时,对应不上的变成undefined
let [a, b, c] = [1, 2];
console.log(a, b, c);

Insert image description here

// 变量默认值,声明变量时将c默认成6
let [a, b, c = 6] = [1, 2];
console.log(a, b, c);

Insert image description here

// 分割数组,将1赋值给a,2,3成一个新数组
let [a, ...other] = [1, 2, 3];
console.log(a, other);

Insert image description here

// 空内容,将a赋值为1,b赋值为3
let [a,,b] = [1, 2, 3];
console.log(a, b);

Insert image description here

(3) Object deconstruction

//1赋值为a,2赋值为b
let {
    
     a, b } = {
    
     a: 1, b: 2 };
console.log(a, b);

Insert image description here

//重命名
let {
    
     a: aa, b: bb } = {
    
     a: 1, b: 2 };
console.log(aa, bb);

Insert image description here

(4) Read the data returned by the interface

function fun() {
    
    
  return {
    
    
    name: "张三",
    hobby: [
      {
    
    
        title: "篮球",
      },
      {
    
    
        title: "唱",
      },
      {
    
    
        title: "RAP",
      },
      {
    
    
        title: "跳",
      },
    ],
  };
}
let {
    
    
  name,
  hobby: [{
    
     title }],
} = fun();
console.log(name, title);

3. New data manipulation methods in ES6

3.1.New string methods provided by ES6

(1) New API

method describe
includes(string, index) Determine whether the string contains the specified string, the return value is a Boolean value
startsWith(string, index) Determine whether the beginning of the string contains the specified string, the return value is a Boolean value
endsWith(string, index) Determine whether the end of the string contains the specified string, the return value is a Boolean value
repeat(n) The repeat() method returns a new string, which means repeating the original string n times.
padStart(length, str) String completion, used for header completion
padEnd(length, str) String completion, used for tail completion
//判断str是否包含an
let str = 'lixiang';
console.log(str.includes('an'));
//从下标为5的字符开始判断是否含an
console.log(str.includes('an',5));

Insert image description here

//判断str是否以l开头
let str = 'lixiang';
console.log(str.startsWith('l'));
//从下标为3的字符开始判断是否以l开头
console.log(str.startsWith('l',3));

Insert image description here

//判断str是否以g结尾
let str = 'lixiang';
console.log(str.endsWith('g'));
//从下标为3的字符开始判断是否以g结尾
console.log(str.startsWith('g',3));

Insert image description here

//入参数字为2,重复两次
let str = 'lixiang';
console.log(str.repeat(2));

Insert image description here

//在lixiang前面补a,补够10位
let str = 'lixiang';
console.log(str.padStart(10, 'a'));

Insert image description here

//在lixiang后面补a,补够10位
let str = 'lixiang';
console.log(str.padEnd(10, 'a'));

Insert image description here

(2) Template string

In ES5, we often write string concatenation like this.

const name = '李祥';
const age = 18;
const hobbies = '写代码';
const str = '我叫'+name+',今年'+age+'岁,'+'喜欢'+hobbies+'。'

The template string newly introduced in ES6 is written as follows.

const str = `我叫${
      
      name},今年${
      
      age}岁,喜欢${
      
      hobbies}`
console.log(str);

Insert image description here

(3) Precautions when using template strings

  • When using template strings to represent multiline strings, all whitespace and indentation will be preserved in the output.
  • To introduce variables into the template string, they must be introduced in the form ${variable name}.
  • Any JavaScript expression can be placed inside the ${…} braces in the template string, which can perform operations, reference object properties, call functions, even nest them, and even call itself.
3.2.Usage of ES6 spread operator

(1) Deep copy one-dimensional array

const list = [1, 2, 3, 4, 5];
const listCopy = [...list];
console.log(listCopy);

Insert image description here

(2) Split the array

const list = [1, 2, 3, 4, 5];
const [, ...list1] = list;
console.log(list1);

Insert image description here

(3) Convert the array into parameters and pass them to the function

const list = [1, 2];
function fun(a, b) {
    
    
  console.log(a + b);
}
fun(...list);

Insert image description here

3.3.ES6 array extension methods

(1) fill: Replacing elements in the array will change the original array. If you want to keep the value of the original array unchanged, you can use deep copy.

const list = [1, 2, 3, 4, 5];
//全部替换成6
const list1 = [...list].fill(6);
//下标从1开始到下表为4之间左闭右开,全部替换成6
const list2 = [...list].fill(6, 1, 4);
console.log(list);
console.log(list1);
console.log(list2);

Insert image description here

(2) find: Query the elements in the array that meet the conditions.

const list = [
  {
    
     name: "李祥", age: 15 },
  {
    
     name: "张三", age: 10 },
  {
    
     name: "李四", age: 19 },
  {
    
     name: "王武", age: 20 },
];
const result = list.find(function (item) {
    
    
  return item.name === "李祥";
});
console.log(result);

Insert image description here

(3) findIndex: Query the index of the element in the array that meets the conditions.

const result = list.findIndex(function (item) {
    
    
  return item.name === "李祥";
});
console.log(result);

Insert image description here

(4) flat: used to merge arrays.

const list = [1, 2, 3, [4, 5, 6, [ 7, 8]]];
const list2 = list.flat(2);
console.log(list2);

Insert image description here

(5) Filter: Filter out elements that meet the conditions. Unlike find, filter returns an array.

const result = list.filter(function (item) {
    
    
  return item.name === "李祥";
});
console.log(result);

Insert image description here

3.4.map method in ES6 array

map is used to convert numbers of one type into another type.

const list = [
  {
    
     name: "李祥", age: 15 },
  {
    
     name: "张三", age: 10 },
  {
    
     name: "李四", age: 19 },
  {
    
     name: "王武", age: 20 },
];
//遍历集合中每一项,创建obj对象,将原对象属性复制到新的obj中
//然后给obj增加一个属性state
const mapList = list.map(function (i) {
    
    
  let obj = {
    
    };
  //对象拷贝
  Object.assign(obj, i);
  obj.sex = 0;
  return obj;
});
console.log(mapList);

Insert image description here

3.5.New features of ES6 objects

Create object

const a = {
    
    
  name: 'lixiang',
  age: 21,
  address: {
    
    
    city: 'BeiJing',
    town: 'ChangYang'
  },
};

(1) Deep copy simple objects

const b = {
    
     ...a };
console.log(b);

Insert image description here

(2) Set default values ​​for objects

const b = {
    
     ...a, name: 'zhangsan' };
console.log(b);

Insert image description here

(3) Merge objects

const b = {
    
     sex:'0' };
const c = {
    
    ...a,...b}
console.log(c);

Insert image description here

(4) Abbreviation of attribute initialization and method

Insert image description here

(5) New methods added to Object

  • Object.is: Determine whether two objects are equal
let res = Object.is({
    
    name:'lx'}, {
    
    name:'lx'});
console.log(res);
let res1 = Object.is(NaN, NaN);
console.log(res1);

Insert image description here

  • Object.assign: Object copy
let a = {
    
     name: 'lx', age: 24 };
let b = {
    
    };
let c = Object.assign(b, a);
console.log(c);

Insert image description here

  • Object.keys: Get all the keys of the object
let a = {
    
     name: 'lx', age: 24 };
const arr = Object.keys(a);
console.log(arr);

Insert image description here

  • Object.values: Get all the values ​​of the object
let a = {
    
     name: 'lx', age: 24 };
const arr = Object.values(a);
console.log(arr);

Insert image description here

  • Object.entries: Get key and value
let a = {
    
     name: 'lx', age: 24 };
const arr = Object.entries(a);
console.log(arr);

Insert image description here

3.6.ES6 adds new Map and WeakMap

Objects in JavaScript are essentially collections of key-value pairs, but only strings can be used as key names in objects. In some special scenarios, it cannot meet our needs. Because of this, the data Map is proposed. It is a more complete Hash structure in JavaScript.

Map object: used to save key-value pairs. Any value (object or primitive value) can be used as a key name or a value.

  • Properties and methods
Properties/Methods effect example
size Returns the number of key-value pairs m.size
clear() Clear all key-value pairs m.clear()
has(key) Determine whether there is a specified key name in the key-value pair, the return value is a Boolean value m.has(key)
get(key) Get the key value of the specified key name, if it does not exist, return undefined m.get(key)
set(key, value) Add a key-value pair. If the key name already exists, update the key-value pair. m.set(key, value)
delete(key) Delete the key-value pair of the specified key name m.delete(key)

(1) Create a Map

//创建一个空map
let map = new Map();
//创建一个带有默认值的map
let mapDef = new Map([
    ['name','lx'],
    ['age',12]
]);
console.log(map);
console.log(mapDef);

Insert image description here

(2) API demonstration

//创建一个空map
let map = new Map();
//map中增加一个元素
map.set('name','lx');
map.set('age',20);
console.log(map);
//map中修改一个元素
//map中set方法如果有key则覆盖,没有则新增
map.set('name','zs');
console.log(map);
//返回键值对的数量
console.log(map.size);
//判断是否有某个key
console.log(map.has('name'));
//获取某个key的value
console.log(map.get('name'));
//删除某个key
map.delete('name');
console.log(map);
//清空
map.clear();
console.log(map);

Insert image description here

(3) Traverser generation function

const keys = map.keys();
const values = map.values();
const entries = map.entries();
console.log(Array.from(keys));
console.log(Array.from(values));
console.log(Array.from(entries));

Insert image description here

WeakMap: only accepts objects as key names and cannot be traversed

const weakMap = new WeakMap([[{
    
     name: 'lx' ,age: 21},{
    
    id:1,hobby:'唱、跳、rap、篮球'}]]);
console.log(weakMap);

Insert image description here

Insert image description here

3.7.ES6 adds Set and WeakSet

Set is an array-like data structure provided to developers by ES6, which can be understood as a collection of values. The biggest difference between it and an array is that its values ​​will not have duplicates.

Set ensures unique member values ​​and is used for collection deduplication.

  • Properties and methods
Properties/Methods effect example
add Add new element s.add(key)
size Return the number of members s.size
clear() Clear all members s.clear()
has(value) Determine whether there is a specified value in the key-value pair, the return value is a Boolean value s.has(key)
delete(value) Delete specified value s.delete(key)

(1) Create a Set

const a = {
    
     name: 'lx' };
const set = new Set([a]);
console.log(set);

const list = new Set([1, 2, 3, 4]);
console.log(list);

Insert image description here

(2) API demonstration

const set = new Set([1, 2, 3, 4]);
console.log(set);
//获取set长度
console.log(set.size);
//判断是否存在2元素
console.log(set.has(2));
//删除2元素
set.delete(2);
console.log(set.has(2));

Insert image description here

WeakSet: Array members must be objects

  • The WeakSet structure also provides the add() method, delete() method, and has() method for developers to use. Their functions and usage are exactly the same as the Set structure.
  • WeakSet structures are not traversable. Because its members are all weak references to the object, they can be recycled by the recycling mechanism at any time and the members disappear. Therefore, the WeakSet structure will not have keys(), values(), entries(), forEach() and other methods and size attributes.
3.8.Conversion between Array and Set
// 数组转set
const list = [1, 2, 3];
const set = new Set(list);
console.log(set);

// set转数组
const arr = Array.from(set);
console.log(arr);
3.9.Conversion between Object and Map
// 对象转map
const obj = {
    
     nane: 'lx', age:24 };
const map = new Map(Object.entries(obj));
console.log(map);

// map转对象
const obj1 = Object.fromEntries(map);
console.log(obj1);

4.ES6 adds new high-level knowledge points

4.1. New proxy Proxy in ES6

(1) Introduction to Proxy

As the English translation of Proxy shows, Proxy is an API introduced by ES6 to operate objects. It does not act directly on the object, but acts as a medium. If the object needs to be manipulated, the consent of the medium is required.

(2) How to use

/* @params
** target: 用Proxy包装的目标对象
** handler: 一个对象,对代理对象进行拦截操作的函数,如set、get
*/
let p = new Proxy(target, handler)

(3) Case practice

const house = {
    
    
  name: '三室一厅-次卧',
  price: 1000,
  phone: '18823139921',
  id: '20230131',
  state: '**',
};

const handle = {
    
    
  get: function (obj, key) {
    
    
    switch (key) {
    
    
      case 'price':
        return obj[key] + 500;
      case 'phone':
        return obj[key].substring(0, 3) + '****' + obj[key].substring(7);
      default:
        return obj[key];
    }
  },
  set: function (obj, key, value) {
    
    
    if (key === 'state') {
    
    
      obj[key] = value;
    }
  },
};

const houseproxy = new Proxy(house, handle);
console.log(houseproxy.id);
console.log(houseproxy.phone);
console.log(houseproxy.price);
houseproxy.state='****';
console.log(houseproxy.state);

Insert image description here

4.2. New reflection Refect in ES6

(1) Introduction to Reflect

Like Proxy, Reflect is introduced in ES6 to operate objects. It transplants some methods in the object that are obviously internal to the language to the Reflect object. It modifies the return results of some methods to make them more reasonable and more efficient. Semantic, and uses functions to implement imperative operations on Object.

  • Properties and methods
Properties/Methods effect
Reflect.apply(target, thisArg, args) When calling a function, an array can be passed in as a calling parameter.
Reflect.construct(target, args) Performing a new operation on the constructor is equivalent to executing new target(...args).
Reflect.get(target,name, receiver) Get the value of an attribute on the object, similar to target[name]. If there is no such attribute, undefined is returned.
Reflect.set(target, name,value, receiver) The Reflect.defineProperty method is basically equivalent to Object.defineProperty, which directly defines a new property on an object or modifies an existing property of an object. The difference is that Object.defineProperty returns this object. And Reflect.defineProperty will return a Boolean value
Reflect.has(target,name) Determining whether an object has a certain attribute has the same function as the in operator.
Reflect.ownKeys(target) Returns an array containing all its own properties (excluding inherited properties). (Similar to Object.keys(), but not affected by enumerable, Object.keys returns a string array of all enumerable properties).
Reflect.isExtensible(target) Determine whether an object is extensible (whether new properties can be added to it), similar to Object.isExtensible(). Returns a Boolean indicating whether the given object is extendable. (Both the Object.seal or Object.freeze methods can mark an object as non-extensible.)
Reflect.preventExtensions(target) Make an object non-extensible, meaning that new properties can never be added.
4.3.Proxy implements two-way data binding

(1) Demand

Implement a two-way data binding.

Insert image description here

(2) Realization

  • Write html code
<body>
    请输入内容:<input type="text" id = "input"/><br/>
    实时内容展示:<span id = "span"></span>
    <script src="./js/index.js"></script>
</body>
  • Write js code
// 获取dom节点
const input = document.getElementById("input");
const span = document.getElementById("span");
//定义双向绑定的对象
let obj = {
    
    };

//定义代理对象的handle方法
const handle = {
    
    
  get: function (target, key) {
    
    
    return target[key];
  },
  set: function (target, key, value) {
    
    
    if (key === "text" && value) {
    
    
      span.innerHTML = value;
      return (target[key] = value);
    }
  },
};

//创建代理对象
const proxy = new Proxy(obj, handle);

//创建键盘的监听事件
input.addEventListener("keyup", function (e) {
    
    
  proxy.text = e.target.value;
  console.log(proxy.text);
});

5. Function extension, class and modularization

5.1. Expansion of function parameters

(1) Function parameters can be set to default values

//求和方法,当a和b都不传值时,默认都为1
function sum(a = 1, b = 1) {
    
    
  return a + b;
}
console.log(sum());
console.log(sum(3));
console.log(sum(3,5));

Insert image description here

(2) rest parameters, variable parameters

//求和方法,可变参数
function sum(...rest) {
    
    
    let num = 0;
    rest.forEach((e)=>{
    
    
        num+=e;
    })
  return num;
}
console.log(sum(...[1,2]));
console.log(sum(...[1,2,4]));

Insert image description here

5.2.ES6 new arrow function

(1) Introduction to arrow functions

ES6 allows using => to define functions. Arrow functions are equivalent to anonymous functions and simplify function definition.

Arrow functions are syntactically simpler than ordinary functions. Arrow functions use arrow => to define functions, omitting the keyword function.

无参:()=>{
    
    },等同于:function (){
    
    }
有参:(a,b)=>{
    
    },等同于:function (a,b){
    
    }

(2) Arrow functions do not bind this

//箭头函数this指当前块级作用域
const obj = {
    
    
  num: 10,
  sum() {
    
    
    setTimeout(() => {
    
    
      console.log(this.num);
    }, 1000);
  },
};
obj.sum();

Insert image description here

If it is not an arrow function, the setTimeout() function call refers to the current window.

const obj = {
    
    
  num: 10,
  sum() {
    
    
    setTimeout(function (){
    
    
      console.log(this);
    }, 1000);
  },
};
obj.sum();

Insert image description here

(3) Under what circumstances cannot arrow functions be used?

  • Define object methods
const obj = {
    
    
  num: 10,
  sum:() => {
    
    
    setTimeout(() => {
    
    
      console.log(this.num);
    }, 1000);
  },
};
obj.sum();

Insert image description here

  • Arrow function has no arguments
const fun = () => {
    
    
  console.log(arguments);
};
fun();

Insert image description here

  • Define constructor
const Car = () => {
    
    
  console.log(this);
};
let car = new Car();

Insert image description here

  • Define callback functions for DOM events
const span = document.getElementById("span");
span.addEventListener("click", () => {
    
    
  console.log(this);
  this.innerHTML = "触发事件";
});

Insert image description here

Insert image description here

const span = document.getElementById("span");
span.addEventListener("click", function () {
    
    
  console.log(this);
  this.innerHTML = "触发事件";
});

Insert image description here

5.3. The concept of classes is newly introduced in ES6

Before ES6, there were only objects in JavaScript and no concept of classes. It is a prototype-based object-oriented language. The characteristic of prototype objects is to share their properties with new objects.

(1) Define class

class Person {
    
    
  constructor(name, age) {
    
    
    this.name = name;
    this.age = age;
  }
  sayHello() {
    
    
    console.log(`我是${
      
      this.name},今年${
      
      this.age}`);
  }
}
const person = new Person("张三", 18);
person.sayHello();
console.log(person);

Insert image description here

(2) Class inheritance, overriding the methods of the parent class

class Person {
    
    
  constructor(name, age) {
    
    
    this.name = name;
    this.age = age;
  }
  hello() {
    
    
    console.log(`我是${
      
      this.name},今年${
      
      this.age}`);
  }
}

class Student extends Person {
    
    
  //子类重写父类属性
  constructor(name, age, sex) {
    
    
    super(name, age);
    this.sex = sex;
  }
  hello() {
    
    
    console.log(`我是${
      
      this.name},今年${
      
      this.age}岁,性别:${
      
      this.sex === '1'?'男':'女'}`);
  }
}

const person = new Student('张三', 18,'1');
person.hello();
console.log(person);

Insert image description here

(3) Static methods and static properties

//静态方法和静态属性只能由类名进行调用
class Person {
    
    
  static eyes = '眼睛';
  static hello(){
    
    
    console.log(`我是${
      
      this.name}`);
  }
}

console.log(Person.eyes);
Person.hello();

Insert image description here

5.4.ES6 adds new modular development

Before ES6, there was no concept of classes, and there was no such thing as a module. Ideally, developers should only focus on the development of core businesses, and can directly introduce other businesses with certain commonality, that is, modules. Multi-player development is how it should be.

  • CommonJS: Commonjs was introduced as a modular specification and native module in Node.
  • AMD and RequireJs: AMD is the abbreviation of "Asynchronous Module Definition", which means "asynchronous module definition". It loads modules asynchronously, and the loading of the module does not affect the execution of subsequent statements. All statements that depend on this module are defined in a callback function. This callback function will not run until all dependencies are loaded (pre-dependencies).

Import and export cases

  • export.js
const name = '李祥';

function hello(){
    
    
  console.log('hello word');
}

class Car{
    
    
  constructor(name){
    
    
    this.name=name;
  }
  run(){
    
    
    console.log(this.name+'跑起来了');
  }
}

export default{
    
    
  name,
  hello,
  Car,
}
  • Import.js
import test from './export.js';
console.log(test.name);
test.hello();
  • The introduction of js in html should be changed to module type
<script src="./js/import.js" type="module"></script>

Insert image description here

6.ES6 improves asynchronous programming

6.1.Promise introduction and cases

(1) What is callback hell?

When asynchronous operations want to be sequential, you can only nest another asynchronous operation within a callback function after the asynchronous success. If there are too many nested levels, callback hell will be formed.

Disadvantages of callback hell: Post-code maintenance is more difficult.

Promises are used to solve callback hell.

Promises encapsulate asynchronous operations. Create a promise object and write a function as a parameter. This function parameter has two parameters, namely resolve and reject. Write asynchronous operations inside the function, call resolve if successful, and call reject if failed. At this time, the promise object can know the status of the asynchronous operation. p.then (successful execution) p.catch (failed execution).

A promise is essentially a state machine that records the status of asynchronous internal operations.

The code was coupled before es6, so when an error occurred, it could not be eliminated.

function request() {
    
    
  axios.get("a.json").then((res) => {
    
    
    if (res && res.data.code === 0) {
    
    
      console.log(res.data.data.data);
      axios.get("b.json").then((res) => {
    
    
        if (res && res.data.code === 0) {
    
    
          console.log(res.data.data.data);
          axios.get("c.json").then((res) => {
    
    
            console.log(res.data.data.data);
          });
        }
      });
    }
  });
}

request();
  • Simply put, Promise is a container that stores the results of an event (usually an asynchronous operation) that will end in the future.
  • Syntactically speaking, a Promise is an object from which the final status (success or failure) of an asynchronous operation can be obtained.
  • Promise is a constructor that provides a unified API. Promise can store not only asynchronous code, but also synchronous code.
// 准备阶段
new Promise((resolve, reject) => {
    
    })

// 成功状态
new Promise((resolve, reject) => {
    
    
  resolve('成功'); // 同步代码
}).then((res) => {
    
    
  console.log(res);
});

// 失败状态
new Promise((resolve, reject) => {
    
    
  reject('失败');
}).catch((err) => {
    
    
  console.log(err);
});

Insert image description here

  • The state of the Promise object is not affected by the outside world

    • pending initial state

    • resolve success status

    • rejected failed status

      Promise has the above three states. Only the result of the asynchronous operation can determine which state it is currently. No other operation can change this state.

  • Once the state of a Promise changes, it will not change again. You can get this result at any time. The state cannot be reversed. It can only change from pending to resolved or from pending to rejected.

(2) Promise solves callback hell case

//先定义三个函数
function requestA() {
    
    
  return new Promise((resolve, reject) => {
    
    
    axios.get("a.json").then((res) => {
    
    
      resolve(res);
    });
  });
}

function requestB() {
    
    
  return new Promise((resolve, reject) => {
    
    
    axios.get("b.json").then((res) => {
    
    
      resolve(res);
    });
  });
}

function requestC() {
    
    
  return new Promise((resolve, reject) => {
    
    
    axios.get("c.json").then((res) => {
    
    
      resolve(res);
    });
  });
}
function request() {
    
    
  requestA().then((res) => {
    
    
      console.log(res);
      return requestB();
    }).then((res) => {
    
    
      console.log(res);
      return requestC();
    }).then((res) => {
    
    
      console.log(res);
    });
}
request();

(3) Promise.all method

  • Promise.all is actually a function that takes an promisearray and returns one promise. Then promiseyou will get the result array when all are completed or throw an error when one of them is rejected.
  • The return value will be in the promiseorder of the parameters, not by promisethe order in which the calls were completed.
function requestAll() {
    
    
  Promise.all([requestA(), requestB(), requestC()])
    .then((res) => {
    
    
      console.log(res);
    })
    .catch((err) => {
    
    
      console.log(err);
    });
}
requestAll();

(4) Promise.race method

Promse.race means racing. promiseWhichever result in the incoming array is obtained faster, that result will be returned, regardless of whether the result itself is a success state or a failure state.

function requestRace() {
    
    
  Promise.race([requestA(), requestB(), requestC()])
    .then((res) => {
    
    
      console.log(res);
    })
    .catch((err) => {
    
    
      console.log(err);
    });
}
requestRace();
6.2. Elegant asynchronous programming async

(1) What is async

async is the abbreviation of asynchronous, the syntactic sugar of Generator, used to declare that a function is an asynchronous function.

async function sum(a,b) {
    
    
  await console.log(a+b);
}
sum(1,2);

asyncWritten before the function, it returns an Promiseobject.

async await transforms promise.then asynchronous call.

async function request() {
    
    
  try {
    
    
    const a = await requestA();
    const b = await requestB();
    const c = await requestC();
    console.log(a, b, c);
  } catch (err) {
    
    
    console.log(err);
  }
}
request();

추천

출처blog.csdn.net/weixin_47533244/article/details/133282741