JS原理课-DAY01
知识点自测
今天课程中涉及到的已学习知识点
- 函数的
call方法-文档链接
1 2 3 4 5 6 7 8 9 10
| function func(food,drink){ console.log(this) console.log(food) console.log(drink) } const obj = { name:'小黑' } func.call(obj,'西蓝花','咖啡')
|
- 函数的
apply方法-文档链接
1 2 3 4 5 6 7 8 9 10
| function func(food,drink){ console.log(this) console.log(food) console.log(drink) } const obj = { name:'小黑' } func.apply(obj,['西蓝花','咖啡'])
|
- 函数的
bind方法-文档链接
1 2 3 4 5 6 7 8 9 10
| function func(food, drink) { console.log(this) console.log(food) console.log(drink) } const obj = { name: '小黑' } const bindFunc = func.bind(obj, '花菜') bindFunc('可乐')
|
- 剩余参数-文档链接
1 2 3 4
| function func(...args){ console.log(args) } func('西蓝花','西葫芦','西洋参','西芹')
|
- Promise核心用法-文档链接
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| const p = new Promise((resolve, reject) => { setTimeout(() => { const num = parseInt(Math.random() * 10) if (num > 5) { resolve(`成功啦--${num}`) } else { reject(`失败啦--${num}`) } }, 1000) }) p.then(res => { console.log(res) }, err => { console.log(err) })
|
- URLSearchParams核心用法-文档链接
1 2 3 4
| const params = new URLSearchParams({ name: 'jack', age: 18 })
console.log(params.toString())
|
- Object.create核心用法-文档链接
1 2 3 4 5 6 7 8 9
| const person = { name: 'itheima', foods: ['西蓝花', '西红柿', '西葫芦'] }
const clone = Object.create(person) clone.name = 'itheima' clone.foods.push('西北风') console.log(clone.foods === person.foods)
|
- Object.assign核心用法-文档链接
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| const person = { name: 'itheima', foods: ['西蓝花', '西红柿', '西葫芦'] } const son = { name: 'rose', }
const returnTarget = Object.assign(son, person)
console.log(returnTarget === son) console.log(son.name) console.log(son.foods === person.foods)
|
JS中的this
这一节咱们来学习JS中this相关的知识点
传送门:MDN-this
传送门:MDN-call
传送门:MDN-apply
传送门:MDN-bind
传送门:MDN-箭头函数
传送门:MDN-剩余参数
传送门:MDN-Symbol
这一节咱们会学习的有:
- 如何确认
this指向
- 如何改变
this指向
- 手写
call,apply,bind
如何确认this的值:
在非严格模式下,总是指向一个对象,在严格模式下可以是任意值,开启严格模式可以使用如下两种方式:
- 在整个脚本顶部开启
- 在函数顶部开启
1 2 3 4 5 6
| 'use strict' function func() { 'use strict' }
|
然后就可以根据不同的模式来确认this指向啦,
全局执行环境中,指向全局对象(非严格模式、严格模式)
函数内部,取决于函数被调用的方式
直接调用的this值:
- 非严格模式:全局对象(window)
- 严格模式:undefined
对象方法调用的this值:
- 调用者
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
|
面试回答:
如何确认this指向:
全局执行环境中,指向全局对象(非严格模式、严格模式)
如何开启严格模式:
1 2 3 4 5 6
| 'use strict' function func() { 'use strict' }
|
函数内部,取决于函数被调用的方式
直接调用的this值:
- 非严格模式:全局对象(window)
- 严格模式:undefined
对象方法调用时的this值为调用者
如何改变this指向
主要有2类改变函数内部this指向的方法:
调用函数并传入具体的this:
call:
- 参数1:
this
- 参数2-n:传递给函数的参数
apply-数组作为参数
- 参数1:
this
- 参数2:以数组的形式,传递给函数的参数
创建绑定this的函数:
- bind:返回一个绑定了
this的新函数
- 箭头函数:最近的this是谁,就是谁
调用函数并传入具体的this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| function funcA(p1, p2) { console.log('funcA-调用') console.log(this) console.log('p1:', p1) console.log('p2:', p2) } const obj = { name: 'jack' }
funcA.call(obj, 1, 2)
funcA.apply(obj, [3, 4])
|
创建绑定this的函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| function funcB(p1, p2) { console.log('funcB-调用') console.log(this) console.log('p1:', p1) console.log('p2:', p2) } const person = { name: 'itheima' }
const bindFuncB = funcB.bind(person, 123) bindFuncB(666)
const student = { name: 'lilei', sayHi: function () { console.log(this) const inner = () => { console.log('inner-调用了') console.log(this) } inner() } } student.sayHi()
|
面试回答:
如何改变this指向,有2类改变this指向的方法,分别是:
调用函数时并传入具体的this
call:从第二个参数开始挨个传递参数
apply:在第二个参数以数组的形式传递参数
创建函数时绑定this?
bind:返回一个绑定了this以及参数(可选)的新函数
箭头函数:创建时会绑定上一级作用域中的this
手写call方法
这一节咱们来实现myCall方法,实际用法和call方法一致,核心步骤有4步
1 2 3 4 5 6 7 8 9 10 11 12 13
| const person = { name: 'itheima' } function func(numA, numB) { console.log(this) console.log(numA, numB) return numA + numB }
const res = func.myCall(person, 2, 8) console.log('返回值为:', res)
|
- 如何定义
myCall?
- 如何让函数内部的
this为某个对象?
- 如何让
myCall接收参数2-参数n?
- 使用Symbol调优
myCall?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| Function.prototype.myCall = function () { }
Function.prototype.myCall = function (thisArg) { thisArg['fn'] = this const res = thisArg['fn']() delete thisArg['fn']
}
Function.prototype.myCall = function (thisArg, ...args) { thisArg['fn'] = this const res = thisArg['fn'](...args) delete thisArg['fn'] return res }
Function.prototype.myCall = function (thisArg, ...args) { const fn = Symbol() thisArg[fn] = this const res = thisArg[fn](...args) delete thisArg[fn] return res }
const person = { name: 'itheima' } function func(numA, numB) { console.log(this) console.log(numA, numB) return numA + numB }
const res = func.myCall(person, 2, 8) console.log('返回值为:', res)
|
面试回答:
手写call方法的步骤为
- 在
function的原型上添加myCall方法,保证所有函数都可以调用
- 方法内部,通过动态为对象添加方法的形式来指定
this指向
- 调用完毕之后通过
delete关键字删除上一步动态增加的方法
- 方法的名字通过Symbol进行设置,避免和默认名重复
- 使用剩余参数的形式传递参数2-参数n(函数参数)
1 2 3 4 5 6 7
| Function.prototype.myCall = function (thisArg, ...args) { const fn = Symbol() thisArg[fn] = this const res = thisArg[fn](...args) delete thisArg[fn] return res }
|
手写apply方法
这一节咱们来实现myApply方法,实际用法和apply方法一致,核心步骤依旧4步
1 2 3 4 5 6 7 8 9 10 11 12 13
| const person = { name: 'itheima’ }
function func(numA, numB) { console.log(this) console.log(numA, numB) return numA + numB }
const res = func.myApply(person, [2, 8]) console.log('返回值为:', res)
|
如何定义myApply?
- 定义在原型上
如何让函数内部的this为某个对象?
- 动态给对象添加方法,通过
对象.方法()调用即可
- 使用
Symbol来生成方法名
如何让myApply接收参数?
- 定义参数2即可
- 传递给原函数时需要使用
...展开
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| Function.prototype.myApply = function () { }
Function.prototype.myApply = function (thisArg) { const fn = Symbol() thisArg[fn] = this const res = thisArg[fn](...args) delete thisArg[fn] return res }
Function.prototype.myApply = function (thisArg, args) { const fn = Symbol() thisArg[fn] = this const res = thisArg[fn](...args) delete thisArg['fn'] return res }
const person = { name: 'itheima’ }
function func(numA, numB) { console.log(this) console.log(numA, numB) return numA + numB }
const res = func.myApply(person, [2, 8]) console.log('返回值为:', res)
|
面试回答:
手写apply方法
- 在
function的原型上添加myApply方法,保证所有函数都可以调用
- 方法内部,通过动态为对象添加方法的形式来指定
this指向
- 调用完毕之后通过
delete关键字删除上一步动态增加的方法
- 方法的名字通过Symbol进行设置,避免和默认名重复
- 直接使用数组传递函数的参数,内部调用时结合
...运算符展开数组
1 2 3 4 5 6 7
| Function.prototype.myApply = function (thisArg, args) { const fn = Symbol() thisArg[fn] = this const res = thisArg[fn](...args) delete thisArg[fn] return res }
|
手写bind方法
这一节咱们来实现myBind方法,实际用法和bind方法一致,核心步骤为2步
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| const person = { name: 'itheima' }
function func(numA, numB, numC, numD) { console.log(this) console.log(numA, numB, numC, numD) return numA + numB + numC + numD }
const bindFunc = func.myBind(person, 1, 2)
const res = bindFunc(3, 4) console.log('返回值:', res)
|
- 如何返回一个绑定了
this的函数?
- 如何实现绑定的参数,及传入的参数合并?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| Function.prototype.myBind = function (thisArg) { return () => { this.call(thisArg) } }
Function.prototype.myBind = function (thisArg, ...args) { return (...args2) => { return this.call(thisArg, ...args, ...args2) } }
const person = { name: 'itheima' }
function func(numA, numB, numC, numD) { console.log(this) console.log(numA, numB, numC, numD) return numA + numB + numC + numD }
const bindFunc = func.myBind(person, 1, 2)
const res = bindFunc(3, 4) console.log('返回值:', res)
|
面试回答
手写bind方法
function原型上添加myBind函数,参数1为绑定的this,参数2-参数2为绑定的参数
- 内部返回一个新箭头函数,目的是绑定作用域中的this
- 返回的函数内部,通过
call进行this和参数绑定
- 通过
call的参数2和参数3指定绑定的参数,和调用时传递的参数
1 2 3 4 5
| Function.prototype.myBind = function (thisArg, ...args) { return (...args2) => { return this.call(thisArg, ...args, ...args2) } }
|
JS继承-ES5
这一节咱们来学习如何在JS中实现继承,首先看看在ES6之前可以如何实现继承
传送门:继承与原型链
传送门:继承(计算机科学)
传送门:JavaScript高级程序设计
传送门:MDN-Object.create
传送门:MDN-Object.assign
**继承:**继承可以使子类具有父类的各种属性和方法,而不需要再次编写相同的代码
这一节咱们会学习ES5中常见的继承写法(命名来源于 《JavaScript高级程序设计》)
- 原型链实现继承
- 构造函数继承
- 组合继承
- 原型式继承
- 寄生式继承
- 寄生组合式继承
1 2 3 4 5 6 7 8
| function Parent(){ this.name = name this.foods = ['西蓝花', '西红柿'] this.sayFoods = function () { console.log(this.foods) } }
|
ES5-原型链实现继承
**核心步骤:**希望继承谁,就将谁作为原型
**缺点:**父类中的引用数据类型,会被所有子类共享
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| function Parent(name) { this.name = name this.foods = ['西蓝花', '西红柿'] this.sayFoods = function () { console.log(this.foods) } }
function Son() { }
Son.prototype = new Parent('jack') const s1 = new Son() s1.sayFoods()
const s2 = new Son() s2.sayFoods()
s2.foods.push('西葫芦')
s2.sayFoods() s1.sayFoods()
|
面试回答:
ES5-原型链实现继承
- 将父类的实例作为子类的原型实现继承
- 这种继承方法的缺点是父类中的引用类型数据会被所有子类共享
ES5-构造函数继承
**核心步骤:**在子类的构造函数中通过call或apply父类的构造函数
**缺点:**子类没法使用父类原型上的属性/方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| function Parent(name) { this.name = name } Parent.prototype.sayHi = function () { console.log('你好,我叫:', this.name) }
function Son(name) { Parent.call(this, name) }
const s1 = new Son('lucy') const s2 = new Son('rose') s1.sayHi()
|
面试回答:
ES5-构造函数继承
- 在子类的构造函数中通过
call或者apply调用父类的构造函数
- 这种继承方法的缺点是:子类没法使用父类原型上的属性/方法
ES5-组合继承
通过组合继承,结合上面2种方法的优点
核心步骤:
- 通过原型链继承公共的属性和方法
- 通过构造函数继承实例独有的属性和方法
**特点:**调用了2次构造函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| function Person(name) { this.name = name }
Person.prototype.sayHi = function () { console.log(`你好,我叫${this.name}`) }
function Student(name, age) { Person.call(this, name) this.age = age }
Student.prototype = new Person()
const s = new Student('李雷', 18)
|
面试回答:
ES5-组合继承
组合继承的核心步骤有2步:
- 通过原型链继承公共的属性和方法
- 通过构造函数继承实例独有的属性和方法
组合继承的特点:调用2次父类的构造函数,浪费性能
ES5-原型式继承
直接基于对象实现继承
**核心步骤:**对某个对象进行浅拷贝(工厂函数或Object.create),实现继承
**缺点:**父类中的引用数据类型,会被所有子类共享
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| function objectFactory(obj) { function Fun() { } Fun.prototype = obj return new Fun() } const parent = { name: 'parent', age: 25, friend: ['rose', 'ice', 'robot'], sayHi() { console.log(this.name, this.age) } } const son1 = objectFactory(parent) const son2 = objectFactory(parent) son1.friend.push('lucy') console.log(son2.friend)
|
面试回答:
ES5-原型式继承
- 原型式继承的核心步骤是:对某个对象进行浅拷贝,可以通过内置api
Object.create实现,不需要调用构造函数即可实现继承,主要针对于继承对象的情况
- 原型式继承的缺点是:父类中的引用数据类型,会被所有子类共享
ES5-寄生式继承
核心步骤:
定义工厂函数,并在内部:
- 对传入的对象进行浅拷贝(公共属性/方法)
- 为浅拷贝对象增加属性/方法(独有属性/方法)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| function createAnother(origin) { const clone = Object.create(origin) clone.sayHi = function () { console.log('你好') } return clone } const parent = { name: 'parent', foods: ['西蓝花', '炒蛋', '花菜'] } const son1 = createAnother(parent) const son2 = createAnother(parent)
|
面试回答:
寄生式继承
寄生式继承的核心步骤是:基于对象创建新对象(可以使用Object.create),并且为新创建的对象增加新的属性和方法
寄生式继承和上一节学习的原型式继承的区别是:创建出来的新对象,会额外的增加新的属性/方法
ES5-寄生组合式继承
所谓寄生组合式继承,即通过借用构造函数来继承属性,通过原型链的混成形式来继承方法。其背 后的基本思路是:不必为了指定子类型的原型而调用超类型的构造函数,我们所需要的无非就是超类型 原型的一个副本而已。
核心步骤:
- 通过构造函数来继承属性
- 通过原型链来继承方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| function inheritPrototype(son, parent){ const prototype = object.create(parent.prototype) prototype.constructor = son son.prototype = prototype }
function Parent(name) { this.name = name this.foods = ['西蓝花', '西葫芦', '西红柿'] }
Parent.prototype.sayHi = function () { console.log(this.name, `我喜欢吃,${this.foods}`) }
function Son(name, age) { Parent.call(this, name) this.age = age }
inheritPrototype(Son,Parent)
Son.prototype.sayAge = function () { console.log('我的年龄是', this.age) }
const son1 = new Son('jack', 18) const son2 = new Son('rose', 16)
|
面试回答:
ES5-寄生组合式继承
- 寄生组合式继承的核心步骤是:通过构造函数来继承属性,通过原型链来继承方法
- 寄生组合式继承和组合式继承的区别是:原型链的继承并没有调用父类的构造函数,而是直接基于父类的原型创建一个新副本实现继承
JS继承-ES6
这一节咱们来学习在ES6中class关键字的使用,并且使用它来实现继承
传送门:mdn类
传送门:阮一峰ES6-class
传送门:mdn-super
ES6中推出了class类,是用来创建对象的模板.class可以看作是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。
这一节咱们会学习:
- class核心语法
- class实现继承
- class语法补充
class核心语法
核心语法:
- 如何定义及使用类:
- 如何定义实例属性/方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Person { name food constructor(name, food) { this.name = name this.food = food }
sayHi() { console.log(`你好,我叫${this.name},我喜欢吃${this.food}`) } } const p = new Person('小黑', '西蓝花') p.sayHi()
|
面试回答:
class核心语法:
- 通过
class 类名{}的形式来定义类
- 内部直接写实例属性,可以设置默认值,
- 实例方法的添加方式为
方法名(){}
- 构造函数通过
constructor进行添加
- 通过
new 类名()创建实例,会调用构造函数constructor
1 2 3 4 5 6 7 8 9 10 11
| class Person{ name food='西兰花炒蛋' constructor(name){ this.name=name } sayHi(){ console.log('你好,我叫:',this.name) } }
|
class实现继承
关键语法:
- 子类通过extends继承父类
- 子类构造函数中通过super调用父类构造函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class Student extends Person { song constructor(name, food, song) { super(name, food) this.song = song } sing() { console.log(`我叫${this.name},我喜欢唱${this.song}`) } } const s = new Student('李雷', '花菜', '孤勇者') s.sayHi() s.sing()
|
面试回答:
class实现继承
- 子类通过
extends继承继承父类
- 子类如果需要重新定义构造函数,必须在内部通过
super关键字调用父类的构造函数
class私有,静态属性和方法
补充语法:
- 私有属性/方法的定义及使用(内部调用)
- 静态属性/方法的定义及使用(类直接访问)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| class Person { constructor(name) { this.name = name } #secret = '我有一个小秘密,就不告诉你' #say() { console.log('私有的say方法') } info() { console.log(this.#secret) this.#say() }
static staticMethod() { console.log('这是一个静态方法') console.log(this) } static info = '直立行走,双手双脚' }
const p = new Person('jack') console.log(p)
console.log(p['#secret']) p.info()
Person.staticMethod() console.log(Person.info)
|
面试回答:
class语法补充
class中私有属性/方法
- 定义和使用时需要使用关键字
#
- 私有属性只能在类的内部使用,外部无法使用(代码中)
- Chrome的控制台中为了方便调试,可以直接访问
class中静态属性/方法
- 定义和使用时需要使用关键字
static
- 通过类访问
- 静态方法中的
this是类
fetch
这一节咱们来学习内置函数fetch
传送门-fetch
传送门-Response
传送门-Headers
ajax&axios&fetch的关系:
ajax:ajax 是一种基于原生 JavaScript 的异步请求技术。它使用 XMLHttpRequest 对象来发送请求和接收响应。
axios:axios 是一个基于 Promise 的 HTTP 客户端,可以在浏览器和 Node.js 中使用。它提供了更高级别的封装,使发送请求和处理响应更加简单和灵活。
fetch:fetch 是浏览器内置的 API,用于发送网络请求。它提供了一种现代化、基于 Promise 的方式来进行网络通信。用法和axios类似,但相比于 axios,它的功能和封装级别更为简单。
全局的fetch函数用来发起获取资源请求.他返回一个promise,这个promise会在请求响应后被resolve,并传回Response对象
这一节咱们会学习的有:
fetch核心语法
fetch结合URLSearchParams发送get请求:
const obj = {
name:'jack',
age:18
}
name=jack&age=17
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| 3. `fetch`发送post请求,提交`FormData`数据
4. `fetch`发送post请求,提交`JSON`数据
#### fetch核心语法
**核心语法:**
1. 如何[发请求](https://developer.mozilla.org/zh-CN/docs/Web/API/fetch): 2. 如何处理[响应](https://developer.mozilla.org/zh-CN/docs/Web/API/Response): 3. 注:[测试用接口](https://apifox.com/apidoc/project-1937884/api-49760223)
```javascript fetch(资源地址,{...配置项对象}) .then(response=>{ // 接收请求 })
|
面试回答:
fetch核心语法
fetch函数的参数:
- 参数1:请求的url地址
- 参数2:以对象的形式设置请求相关的内容比如,方法,请求头,提交的数据等.
fetch获取到响应结果,需要如何解析:
1 2 3 4
| fetch(参数1,参数2) .then(response=>{ })
|
fetch结合URLSearchParams发送get请求:
需求:
- 使用
fetch结合URLSearchParams调用地区查询接口
1 2 3 4 5 6 7 8 9 10 11
| ;(async function () { const params = new URLSearchParams({ pname: '广东省', cname: '广州市' }) const url = `http://hmajax.itheima.net/api/area?${params.toString()}` const res = await fetch(url) const data = await res.json() })()
|
面试回答:
fetch结合URLSearchParams发送get请求:
fetch发送get请求时,不需要设置请求方法,因为默认的就是get
URLSearchParams可以用来创建或者解析查询字符串,这里通过它将对象转为查询字符串
post请求-提交JSON
需求:
fetch发送post请求,提交JSON数据
- 测试接口-用户注册
核心步骤:
- 根据文档设置请求头
- 通过配置项设置,请求方法,请求头,请求体
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| ; (async function () { const headers = new Headers() headers.append('content-type', 'application/json') const res = await fetch('http://hmajax.itheima.net/api/register', { method: 'post', headers, body: JSON.stringify({ username: 'itheima9876', password: '123456' }) }) const json = await res.json() console.log(json) })()
|
面试回答:
post请求-提交JSON
fetch函数的第二个参数可以设置请求头,请求方法,请求体,根据接口文档设置对应的内容即可
- 可以通过
JSON.stringify将对象转为JSON
post请求-提交FormData
需求:
fetch发送post请求,提交FormData数据(上传+回显)
- 测试接口-上传图片
核心步骤:
- 通过
FormData添加文件
- 通过配置项设置,请求方法,请求体(
FormData不需要设置请求头)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <input type="file" class="file" accept="image/*"> <script> document.querySelector('.file').addEventListener('change', async function (e) { const data = new FormData() data.append('img', this.files[0]) const res = await fetch('http://hmajax.itheima.net/api/uploadimg', { method: 'post', body: data }) const json = await res.json() console.log(json) }) </script>
|
面试回答:
post请求-提交FormData
fetch提交FormData时不需要额外的设置请求头
实例化FormData之后可以通过append(key,value)方法来动态添加数据
ajax&axios&fetch的关系
ajax是一种基于原生JavaScript的异步请求技术,他使用XMLHttpRequest对象来发送请求和接收响应—学习原理时适用
axios是一个基于Promise的http客户端,可以在浏览器和Node.js中使用.他提供了更高级别的封装,使发送请求和处理响应更加简单和灵活—项目开发时适用
fetch是浏览器内置的API,用于发送网络请求.它基于Promise的方式来进行网络通信.和axios类似.但是功能和封装级别比axios更为简单—项目简单,不想导入axios时适用
Generator
这一节咱们来学习generator
传送门-Generator
Generator对象由生成器函数返回并且它符合可迭代协议和迭代器协议.他可以用来控制流程,语法行为和之前学习的函数不一样
Generator-核心语法
核心语法:
- 如何定义生成器函数:
- 如何获取
generator对象
yield表达式的使用
- 通过
for of获取每一个yield的值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| function* foo() { yield 'a' yield 'b' yield 'c' return 'd' }
const f = foo()
const res1 = f.next() console.log(res1) const res2 = f.next() console.log(res2) const res3 = f.next() console.log(res3)
const res4 = f.next() console.log(res4)
const res5 = f.next() console.log(res5)
const f2 = foo() for (const iterator of f2) { console.log(iterator) }
|
面试回答:
Generator-核心语法
- 可以通过生成器函数(
function* xxx(){})来生成Generator对象:
- 通过
Generator对象的next方法可以获取yield表达式之后的结果
Generator-id生成器
**需求:**使用Generator实现一个id生成器id
1 2 3 4 5 6 7 8 9 10
| function* idGenerator() { } const idMaker = idGenerator()
const { value: id1 } = idMaker.next() console.log(id1) const { value: id2 } = idMaker.next() console.log(id2)
|
核心步骤:
- 定义生成器函数
- 内部使用循环,通过
yield返回id并累加
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| function* generator() { let id = 0 while (true) { yield id++ } }
const idMaker = generator()
const { value: id1 } = idMaker.next() console.log(id1) const { value: id2 } = idMaker.next() console.log(id2)
|
面试回答:
Generator-id生成器
- 生成器函数内部的代码会在调用
next方法时执行,利用这一特点,可以实现任意的生成器,需要时调用next即可获取结果
Generator-流程控制
遇到yield表达式时会暂停后续的操作
**需求:**使用Generator实现流程控制
1 2 3 4 5 6 7 8
| function* weatherGenerator() { yield axios() }
const weather = weatherGenerator()
weather.next()
|
核心步骤:
yield后面跟上天气查询逻辑
- 接口文档-天气预报
- 参考
code:北京 110100 上海 310100 广州 440100 深圳 440300
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| <button class="getWeather">天气查询</button> <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.3.6/axios.js"></script> <script>
function* weatherGenerator() { yield axios('http://hmajax.itheima.net/api/weather?city=110100') yield axios('http://hmajax.itheima.net/api/weather?city=310100') yield axios('http://hmajax.itheima.net/api/weather?city=440100') yield axios('http://hmajax.itheima.net/api/weather?city=440300') }
const cityWeather = weatherGenerator() document.querySelector('.getWeather').addEventListener('click', async () => { const res = await genCity.next() console.log(res) }) </script>
|
面试回答:
Generator-流程控制
- 使用
Generator控制流程的本质是利用yield关键字来分隔逻辑比如示例中依次调用了多个接口,通过yield分隔,通过next来触发调用
参考资料
- 阮一峰-《ECMAScript 6 教程》
- 图灵社区-JavaScript高级程序设计
JS原理课-DAY02
手写Promise
这一节咱们一起来手写Promise
这一章咱们会学习的有:
实现Promise的核心功能:
Promise:
- 实例方法:
catch,finally
- 静态方法:
resolve,reject,race,all,allSettled,any
Promise\A+标准,并跑通872个单元测试
首先明确Promise的核心用法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| const p = new HMPromise((resolve, reject) => { setTimeout(() => { resolve('success') }, 1000); })
p.then(res => { console.log('res:', res) return 'success2' }, err => { console.log('err:', err) }).then(res2 => { console.log('res2:', res2) })
|
手写Promise-构造函数
需求:
- 实现
HMPromise类,可以用如下的方式实例化
- 实例化时传入回调函数
- 回调函数立刻执行
- 回调函数接收函数
resolve和reject
1 2 3 4 5
| const p = new HMPromise((resolve, reject) => { resolve('success') })
|
核心步骤:
- 定义类
HMPromise
- 添加构造函数
constructor
- 定义resolve/reject
- 执行回调函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class HMPromise { constructor(func) { const resolve = (result) => { console.log('resolve-执行啦:', result) } const reject = (result) => { console.log('reject-执行啦:', result) }
func(resolve, reject) } }
|
面试回答:
手写Promise-构造函数
- 定义类
HMPromise,内部添加构造函数constructor,构造函数需要接收回调函数func
- 在构造函数中定义
resolve和reject
- 构造函数内部调用
func并将resolve和reject传入:func(resolve,reject)
手写Promise-状态、成功or失败原因
需求:
HMPromise增加state属性,只能是如下3个值
pending:待定,默认状态
fulfilled:已兑现,操作成功
rejected:已拒绝,操作失败
HMPromise增加result属性,记录成功/失败原因
- 调用
resolve或reject,修改状态,并记录成功/失败原因
1 2 3 4 5 6
| const p = new HMPromise((resolve, reject) => { resolve('success') }) p.state p.result
|
核心步骤:
- 定义常量保存状态,避免硬编码
HMPromise中定义
- 属性:
state保存状态,result成功/失败原因
- 修改
state的私有方法,修改状态并记录result
- 注意:
state只有在pending时,才可以修改,且不可逆
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| const PENDING = 'pending' const FULFILLED = 'fulfilled' const REJECTED = 'rejected' class HMPromise { state = PENDING result = undefined
constructor(func) { const resolve = (result) => { if (this.state === PENDING) { this.state = FULFILLED this.result = result } } const reject = (result) => { if (this.state === PENDING) { this.state = REJECTED this.result = result } }
func(resolve, reject) } }
|
面试回答:
手写Promise-状态、成功or失败原因
- 定义3个常量用来保存状态,
pending,fulfilled,rejected
HMPromise内部定义属性state和result分别用来保存状态和原因
- 调用
resolve时传入具体原因,如果状态为pending则更改状态并记录兑现原因
- 调用
reject时传入具体原因,如果状态为pending则更改状态并记录拒绝原因
手写Promise-then方法-成功和失败回调
需求:
- then方法的回调函数1: 状态变为
fulfilled时触发,并获取成功结果
- then方法的回调函数2: 状态变为
rejected时触发,并获取失败原因
- then方法的回调函数1或2没有传递的特殊情况处理,参考:then方法的参数
1 2 3 4 5 6 7 8 9
| const p = new HMPromise((resolve, reject) => { resolve('success') }) p.then(res => { console.log('成功回调:', res) }, err => { console.log('失败回调:', err) })
|
核心步骤:
- 增加
then方法,根据不同的状态执行对应的回调函数,并传入result
- 参数1:成功的回调函数
- 参数2:失败的回调函数
- 判断参数
- 没有传递
onFulfilled,onRejected时
- 设置默认值(参考文档)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| const PENDING = 'pending' const FULFILLED = 'fulfilled' const REJECTED = 'rejected' class HMPromise { state = PENDING result = undefined
constructor(func) { const resolve = (result) => { if (this.state === PENDING) { this.state = FULFILLED this.result = result } } const reject = (result) => { if (this.state === PENDING) { this.state = REJECTED this.result = result } } func(resolve, reject) }
then(onFulfilled, onRejected) { onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : x => x onRejected = typeof onRejected === 'function' ? onRejected : x => { throw x }
if (this.state === FULFILLED) { onFulfilled(this.result) } else if (this.state === REJECTED) { onRejected(this.result) } } }
|
面试回答
手写Promise-then方法-成功和失败回调
- 添加
then方法,接收2个回调函数:
- 成功回调
onFulfilled
- 失败回调
onRejected
- 判断传入的
onFulfilled和onRejected是否为函数,如果不是设置默认值
- 根据状态调用
onFulfilled或onRejected并传入兑现或拒绝原因
手写Promise-then方法-异步和多次调用
需求:
- 实例化传入的回调函数,内部支持异步操作
then方法支持多次调用(非链式编程)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| const p = new HMPromise((resolve, reject) => { setTimeout(() => { resolve('success') }, 2000); }) p.then(res => { console.log('then1:', res) }, err => { console.log('then1:', err) }) p.then(res => { console.log('then2:', res) }, err => { console.log('then2:', err) })
|
核心步骤:
- 定义属性:保存传入的回调函数:
[]
- 保存回调函数:状态为
pending时
- 调用成功回调:
resolve内部
- 调用失败回调:
reject内部
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| const PENDING = 'pending' const FULFILLED = 'fulfilled' const REJECTED = 'rejected' class HMPromise { state = PENDING result = undefined #handlers = []
constructor(func) { const resolve = (result) => { if (this.state === PENDING) { this.state = FULFILLED this.result = result this.#handlers.forEach(({ onFulfilled }) => { onFulfilled(this.result) }) } } const reject = (result) => { if (this.state === PENDING) { this.state = REJECTED this.result = result this.#handlers.forEach(({ onRejected }) => { onRejected(this.result) }) } } func(resolve, reject) }
then(onFulfilled, onRejected) { onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : x => x onRejected = typeof onRejected === 'function' ? onRejected : x => { throw x }
if (this.state === FULFILLED) { onFulfilled(this.result) } else if (this.state === REJECTED) { onRejected(this.result) } else if (this.state === PENDING) { this.#handlers.push({ onFulfilled, onRejected }) } } }
|
面试回答
手写Promise-then方法-异步和多次调用
HMPromise添加私有属性#handlers
- 保存then方法调用时状态为
pending的回调函数
- 格式为对象数组:
[{onFulfilled,onRejected}...]
构造函数内部调整resolve和reject的逻辑:
- 调用
resolve时取出数组#handlers中的所有onFulfilled回调函数进行调用
- 调用
reject时取出数组#handlers中的所有onRejected回调函数进行调用
手写Promise-异步任务-api补充
- 传送门:MDN-queueMicrotask
- 传送门:MDN-queueMicrotask使用指南
- 传送门:MDN-setImmediate
- 传送门:MDN-MutationObserver
需求:
- 如下代码打印结果为
1,2,4,3
- 核心: 让then方法的回调函数以异步任务的方式执行
1 2 3 4 5 6 7 8
| console.log('top') const p = new HMPromise((resolve, reject) => { resolve('success') }) p.then(res => { console.log(res) }) console.log('bottom')
|
这里我们参考vue2的做法:
- **vue2:**Promise.then、MutationObserver 、 setImmediate 、 setTimeout
- 我们选用:queueMicrotask 、MutationObserver 、 setTimeout
选用原因:
Promise.then: 我们是手写Promise,故不选用这个
queueMicrotask :新式浏览器均支持,node11开始支持,ie不支持
MutationObserver :新式浏览器均支持,ie11开始支持
setImmediate: 新式浏览器只有edge支持,ie10开始支持
setTimeout:浏览器支持,node支持
测试代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
queueMicrotask(() => { })
console.log('top')
const obs = new MutationObserver(() => { console.log('MutationObserver-run') })
const divNode = document.createElement('div')
obs.observe(divNode, { childList: true })
divNode.innerText = 'itheima 666' console.log('bottom')
|
面试回答
请问可以使用哪些方式开启异步任务:
Promise.then: 我们是手写Promise,故不选用这个
queueMicrotask :新式浏览器均支持,node11开始支持,ie不支持
MutationObserver :新式浏览器均支持,ie11开始支持
setImmediate: 新式浏览器只有edge支持,ie10开始支持
setTimeout:浏览器支持,node支持
手写Promise-异步任务-函数封装
需求:
- 封装函数
runMicrotask内部执行异步任务
- 使用
runMicrotask让then方法的回调函数为异步任务
核心步骤:
- 封装函数
runMicrotask并传入回调函数
- 内部依次判断:
queueMicrotask 、MutationObserver 、 setTimeout并使用即可
- 使用
runMicrotask开启执行异步任务即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| function runAsynctask(callback) { if (typeof queueMicrotask === 'function') { queueMicrotask(callback) } else if (typeof MutationObserver === 'function') { const obs = new MutationObserver(callback) const divNode = document.createElement('div') obs.observe(divNode, { childList: true }) divNode.innerText = 'itheima666' } else { setTimeout(callback, 0) } }
const PENDING = 'pending' const FULFILLED = 'fulfilled' const REJECTED = 'rejected' class HMPromise { state = PENDING result = undefined #handlers = []
constructor(func) { const resolve = (result) => { if (this.state === PENDING) { this.state = FULFILLED this.result = result this.#handlers.forEach(({ onFulfilled }) => { onFulfilled(this.result) }) } } const reject = (result) => { if (this.state === PENDING) { this.state = REJECTED this.result = result this.#handlers.forEach(({ onRejected }) => { onRejected(this.result) }) } } func(resolve, reject) }
then(onFulfilled, onRejected) { onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : x => x onRejected = typeof onRejected === 'function' ? onRejected : x => { throw x }
if (this.state === FULFILLED) { runAsynctask(() => { onFulfilled(this.result) }) } else if (this.state === REJECTED) { runAsynctask(() => { onRejected(this.result) }) } else if (this.state === PENDING) { this.#handlers.push({ onFulfilled: () => { runAsynctask(() => { onFulfilled(this.result) }) }, onRejected: () => { runAsynctask(() => { onRejected(this.result) }) } }) } } }
|
面试回答
手写Promise-异步任务-函数封装
封装执行异步任务的函数
定义函数传入异步任务(回调函数)
内部根据实际情况判断并使用开启异步任务的api即可,比如queueMicrotask,MutationObserver
调用的api可以根据实际情况进行调整
如果都无法执行,使用setTimeout兜底
调整then中的逻辑,fulFilled,rejected,pending3种状态时的回调函数,使用封装的函数包装一次
手写Promise-链式编程-fulfilled状态-返回值+异常
需求:
then的链式编程
- 目前只考虑
then的第一个回调函数
- 返回普通值
- 内部出现异常
1 2 3 4 5 6 7 8 9 10 11 12 13
| const p = new HMPromise((resolve, reject) => { resolve(1) }) p.then(res => { console.log(res) return 2 }).then(res => { console.log(res) }, err => { console.log(err) })
|
核心步骤:
- 调整
then方法,返回一个新的HMPromise对象
- 使用
try-catch捕获异常,并通过reject传递
- 内部获取
onFulfilled的执行结果,并通过resolve传递
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
| function runAsynctask(callback) { if (typeof queueMicrotask === 'function') { queueMicrotask(callback) } else if (typeof MutationObserver === 'function') { const obs = new MutationObserver(callback) const divNode = document.createElement('div') obs.observe(divNode, { childList: true }) divNode.innerText = 'itheima666' } else { setTimeout(callback, 0) } }
const PENDING = 'pending' const FULFILLED = 'fulfilled' const REJECTED = 'rejected' class HMPromise { state = PENDING result = undefined #handlers = []
constructor(func) { const resolve = (result) => { if (this.state === PENDING) { this.state = FULFILLED this.result = result this.#handlers.forEach(({ onFulfilled }) => { onFulfilled(this.result) }) } } const reject = (result) => { if (this.state === PENDING) { this.state = REJECTED this.result = result this.#handlers.forEach(({ onRejected }) => { onRejected(this.result) }) } } func(resolve, reject) }
then(onFulfilled, onRejected) { onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : x => x onRejected = typeof onRejected === 'function' ? onRejected : x => { throw x }
const p2 = new HMPromise((resolve, reject) => { if (this.state === FULFILLED) { runAsynctask(() => { try { const x = onFulfilled(this.result) resolve(x) } catch (error) { reject(error) } }) } else if (this.state === REJECTED) { runAsynctask(() => { onRejected(this.result) }) } else if (this.state === PENDING) { this.#handlers.push({ onFulfilled: () => { runAsynctask(() => { onFulfilled(this.result) }) }, onRejected: () => { runAsynctask(() => { onRejected(this.result) }) } }) }
})
return p2 } }
|
面试回答:
手写Promise-链式编程-fulfilled状态-返回值+异常,本节只考虑
- 链式编程的本质then方法会返回一个新的
HMPromise对象
- 将原本的代码迁移到返回的
HMPromise对象的回调函数中
- 内部通过
try-catch捕获异常,出现异常通过reject传递异常
- 获取
onFulfilled的执行结果,并通过resolve传递
手写Promise-链式编程-fulfilled状态-返回Promise
需求:
then的链式编程
- 目前只考虑
then的第一个回调函数
- 返回
Promise
1 2 3 4 5 6 7 8 9 10 11 12 13
| const p = new HMPromise((resolve, reject) => { resolve(1) }) p.then(res => { return new HMPromise((resolve, reject) => { resolve(2) }) }).then(res => { console.log('p2:', res) }, err => { console.log('p2:', err) })
|
核心步骤:
- 判断是否为
HMPromise实例
- 调用
then方法依次传入回调函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
| function runAsynctask(callback) { if (typeof queueMicrotask === 'function') { queueMicrotask(callback) } else if (typeof MutationObserver === 'function') { const obs = new MutationObserver(callback) const divNode = document.createElement('div') obs.observe(divNode, { childList: true }) divNode.innerText = 'itheima666' } else { setTimeout(callback, 0) } }
const PENDING = 'pending' const FULFILLED = 'fulfilled' const REJECTED = 'rejected' class HMPromise { state = PENDING result = undefined #handlers = []
constructor(func) { const resolve = (result) => { if (this.state === PENDING) { this.state = FULFILLED this.result = result this.#handlers.forEach(({ onFulfilled }) => { onFulfilled(this.result) }) } } const reject = (result) => { if (this.state === PENDING) { this.state = REJECTED this.result = result this.#handlers.forEach(({ onRejected }) => { onRejected(this.result) }) } } func(resolve, reject) }
then(onFulfilled, onRejected) { onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : x => x onRejected = typeof onRejected === 'function' ? onRejected : x => { throw x }
const p2 = new HMPromise((resolve, reject) => { if (this.state === FULFILLED) { runAsynctask(() => { try { const x = onFulfilled(this.result) if (x instanceof HMPromise) { x.then(res => resolve(res), err => reject(err)) } else { resolve(x) } } catch (error) { reject(error) } }) } else if (this.state === REJECTED) { runAsynctask(() => { onRejected(this.result) }) } else if (this.state === PENDING) { this.#handlers.push({ onFulfilled: () => { runAsynctask(() => { onFulfilled(this.result) }) }, onRejected: () => { runAsynctask(() => { onRejected(this.result) }) } }) } }) return p2 } }
|
面试回答
手写Promise-链式编程-fulfilled状态-返回Promise
- 判断
onFulfilled的执行结果是否为HMPromise实例
- 如果是的话调用返回值的
then方法,获取兑现和拒绝的原因并通过resolve和reject传递即可
手写Promise-链式编程-fulfilled状态-重复引用
需求:
then中返回的then方法返回的Promise实例报错
- 注:下列代码中的
p2

1 2 3 4 5 6 7 8 9
| const p = new HMPromise((resolve, reject) => { resolve(1) }) const p2 = p.then(res => { return p2 }) p2.then( res => { }, err => console.log('err:', err))
|
核心步骤:
- 判断是否相同,抛出异常
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| function runAsynctask(callback) { if (typeof queueMicrotask === 'function') { queueMicrotask(callback) } else if (typeof MutationObserver === 'function') { const obs = new MutationObserver(callback) const divNode = document.createElement('div') obs.observe(divNode, { childList: true }) divNode.innerText = 'itheima666' } else { setTimeout(callback, 0) } }
const PENDING = 'pending' const FULFILLED = 'fulfilled' const REJECTED = 'rejected' class HMPromise { state = PENDING result = undefined #handlers = []
constructor(func) { const resolve = (result) => { if (this.state === PENDING) { this.state = FULFILLED this.result = result this.#handlers.forEach(({ onFulfilled }) => { onFulfilled(this.result) }) } } const reject = (result) => { if (this.state === PENDING) { this.state = REJECTED this.result = result this.#handlers.forEach(({ onRejected }) => { onRejected(this.result) }) } } func(resolve, reject) }
then(onFulfilled, onRejected) { onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : x => x onRejected = typeof onRejected === 'function' ? onRejected : x => { throw x }
const p2 = new HMPromise((resolve, reject) => { if (this.state === FULFILLED) { runAsynctask(() => { try { const x = onFulfilled(this.result) if (x === p2) { throw new TypeError('Chaining cycle detected for promise #<Promise>') } if (x instanceof HMPromise) { x.then(res => resolve(res), err => reject(err)) } else { resolve(x) } } catch (error) { reject(error) } }) } else if (this.state === REJECTED) { runAsynctask(() => { onRejected(this.result) }) } else if (this.state === PENDING) { this.#handlers.push({ onFulfilled: () => { runAsynctask(() => { onFulfilled(this.result) }) }, onRejected: () => { runAsynctask(() => { onRejected(this.result) }) } }) } }) return p2 } }
|
面试回答
手写Promise-链式编程-fulfilled状态-重复引用
- 判断
onFulfilled函数的返回值是否和then方法内部返回的HMPromise相同
- 如果相同抛出错误
new TypeError('Chaining cycle detected for promise #<Promise>')
手写Promise-链式编程-rejected状态
需求:
then的第二个回调函数,执行reject时的链式编程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| const p = new HMPromise((resolve, reject) => { reject(1) }) const p2 = p.then(undefined, err => { throw 'error' }) p2.then(res => { console.log('p2-res:', res) }, err => { console.log('p2-err:', err) })
|
核心步骤:
- 处理异常:
onRejected的异常
- 获取返回值:
onRejected的返回值
- 将
fulfilled状态中的处理逻辑抽取为函数resolvePromise并复用
fulfilled和rejected状态中调用函数resolvePromise
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
| function runAsynctask(callback) { if (typeof queueMicrotask === 'function') { queueMicrotask(callback) } else if (typeof MutationObserver === 'function') { const obs = new MutationObserver(callback) const divNode = document.createElement('div') obs.observe(divNode, { childList: true }) divNode.innerText = 'itheima666' } else { setTimeout(callback, 0) } }
const PENDING = 'pending' const FULFILLED = 'fulfilled' const REJECTED = 'rejected' class HMPromise { state = PENDING result = undefined #handlers = []
constructor(func) { const resolve = (result) => { if (this.state === PENDING) { this.state = FULFILLED this.result = result this.#handlers.forEach(({ onFulfilled }) => { onFulfilled(this.result) }) } } const reject = (result) => { if (this.state === PENDING) { this.state = REJECTED this.result = result this.#handlers.forEach(({ onRejected }) => { onRejected(this.result) }) } } func(resolve, reject) }
then(onFulfilled, onRejected) { onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : x => x onRejected = typeof onRejected === 'function' ? onRejected : x => { throw x }
const p2 = new HMPromise((resolve, reject) => { if (this.state === FULFILLED) { runAsynctask(() => { try { const x = onFulfilled(this.result) resolvePromise(p2, x, resolve, reject) } catch (error) { reject(error) } }) }
else if (this.state === REJECTED) { runAsynctask(() => { try { const x = onRejected(this.result) resolvePromise(p2, x, resolve, reject) } catch (error) { reject(error) } }) }
else if (this.state === PENDING) { this.#handlers.push({ onFulfilled: () => { runAsynctask(() => { onFulfilled(this.result) }) }, onRejected: () => { runAsynctask(() => { onRejected(this.result) }) } }) } })
return p2 } }
function resolvePromise(p2, x, resolve, reject) { if (x === p2) { throw new TypeError('Chaining cycle detected for promise #<Promise>') } if (x instanceof HMPromise) { x.then(res => resolve(res), err => reject(err)) } else { resolve(x) } }
|
面试回答
手写Promise-链式编程-rejected状态
- 判断
onRejected可能出现的异常,如果出现通过reject传递
- 获取
onRejected函数的执行结果
- 将
fulfilled状态时的处理逻辑抽取为函数,rejected状态时调用函数复用逻辑
手写Promise-链式编程-pending状态
需求:
- 执行异步操作时,支持链式编程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| const p = new HMPromise((resolve, reject) => { setTimeout(() => { resolve(1) }, 2000) }) const p2 = p.then(res => { throw 'error' }) p2.then(res => { console.log('p2-res:', res) }, err => { console.log('p2-err:', err) })
|
核心步骤:
处理异常:
fulfilled状态时推入回调函数数组时增加try-catch
获取返回值:
- 推入数组时,增加获取返回值的操作
调用上一节封装的函数resolvePromise
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
| function runAsynctask(callback) { if (typeof queueMicrotask === 'function') { queueMicrotask(callback) } else if (typeof MutationObserver === 'function') { const obs = new MutationObserver(callback) const divNode = document.createElement('div') obs.observe(divNode, { childList: true }) divNode.innerText = 'itheima666' } else { setTimeout(callback, 0) } }
function resolvePromise(p2, x, resolve, reject) { if (x === p2) { throw new TypeError('Chaining cycle detected for promise #<Promise>') } if (x instanceof HMPromise) { x.then(res => resolve(res), err => reject(err)) } else { resolve(x) } }
const PENDING = 'pending' const FULFILLED = 'fulfilled' const REJECTED = 'rejected' class HMPromise { state = PENDING result = undefined #handlers = []
constructor(func) { const resolve = (result) => { if (this.state === PENDING) { this.state = FULFILLED this.result = result this.#handlers.forEach(({ onFulfilled }) => { onFulfilled(this.result) }) } } const reject = (result) => { if (this.state === PENDING) { this.state = REJECTED this.result = result this.#handlers.forEach(({ onRejected }) => { onRejected(this.result) }) } } func(resolve, reject) }
then(onFulfilled, onRejected) { onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : x => x onRejected = typeof onRejected === 'function' ? onRejected : x => { throw x }
const p2 = new HMPromise((resolve, reject) => { if (this.state === FULFILLED) { runAsynctask(() => { try { const x = onFulfilled(this.result) resolvePromise(p2, x, resolve, reject) } catch (error) { reject(error) } }) }
else if (this.state === REJECTED) { runAsynctask(() => { try { const x = onRejected(this.result) resolvePromise(p2, x, resolve, reject) } catch (error) { reject(error) } }) }
else if (this.state === PENDING) { this.#handlers.push({ onFulfilled: () => { runAsynctask(() => { try { const x = onFulfilled(this.result) resolvePromise(p2, x, resolve, reject) } catch (error) { reject(error) } }) }, onRejected: () => { runAsynctask(() => { try { const x = onRejected(this.result) resolvePromise(p2, x, resolve, reject) } catch (error) { reject(error) } }) } }) } })
return p2 } }
|
面试回答:
手写Promise-链式编程-pending状态
then方法中pending状态时推入数组的函数增加try-catch捕获异常
- 获取推入数组的回调函数的返回值
- 调用上一节封装的函数并传入获取的值
小结:
到目前已经将核心功能全部实现啦,接下来开始实现后续功能
手写Promise-实例方法catch
需求:
- 实现实例方法
catch,可以实现如下调用
1 2 3 4 5 6 7 8 9 10
| const p = new HMPromise((resolve, reject) => { reject('reject-error') }) p.then(res => { console.log('res:', res) }).catch(err => { console.log('err:', err) })
|
核心步骤:
- 参考文档,catch等同于:
then(undefined,onRjected)
- 直接添加
catch方法,内部调用then
- 使用
try-catch包裹constructor中的func捕获异常
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
| function runAsynctask(callback) { if (typeof queueMicrotask === 'function') { queueMicrotask(callback) } else if (typeof MutationObserver === 'function') { const obs = new MutationObserver(callback) const divNode = document.createElement('div') obs.observe(divNode, { childList: true }) divNode.innerText = 'itheima666' } else { setTimeout(callback, 0) } }
function resolvePromise(p2, x, resolve, reject) { if (x === p2) { throw new TypeError('Chaining cycle detected for promise #<Promise>') } if (x instanceof HMPromise) { x.then(res => resolve(res), err => reject(err)) } else { resolve(x) } }
const PENDING = 'pending' const FULFILLED = 'fulfilled' const REJECTED = 'rejected' class HMPromise { state = PENDING result = undefined #handlers = []
constructor(func) { const resolve = (result) => { if (this.state === PENDING) { this.state = FULFILLED this.result = result this.#handlers.forEach(({ onFulfilled }) => { onFulfilled(this.result) }) } }
const reject = (result) => { if (this.state === PENDING) { this.state = REJECTED this.result = result this.#handlers.forEach(({ onRejected }) => { onRejected(this.result) }) } }
try { func(resolve, reject) } catch (error) { reject(error) } }
then(onFulfilled, onRejected) { onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : x => x onRejected = typeof onRejected === 'function' ? onRejected : x => { throw x }
const p2 = new HMPromise((resolve, reject) => { if (this.state === FULFILLED) { runAsynctask(() => { try { const x = onFulfilled(this.result) resolvePromise(p2, x, resolve, reject) } catch (error) { reject(error) } }) }
else if (this.state === REJECTED) { runAsynctask(() => { try { const x = onRejected(this.result) resolvePromise(p2, x, resolve, reject) } catch (error) { reject(error) } }) }
else if (this.state === PENDING) { this.#handlers.push({ onFulfilled: () => { runAsynctask(() => { try { const x = onFulfilled(this.result) resolvePromise(p2, x, resolve, reject) } catch (error) { reject(error) } }) }, onRejected: () => { runAsynctask(() => { try { const x = onRejected(this.result) resolvePromise(p2, x, resolve, reject) } catch (error) { reject(error) } }) } }) } })
return p2 }
catch(onRejected) { return this.then(undefined, onRejected) } }
|
面试回答
手写Promise-实例方法catch
定义catch方法,接收拒绝的回调函数onRejected
catch方法的本质是内部调用then方法
调用形式为第一个回调函数传入undefined,第二个回调函数传入onRejected即可
手写Promise-实例方法finally
需求:
- 无论成功失败都会执行
finally的回调函数
- 回调函数不接受任何参数
1 2 3 4 5 6 7 8 9 10 11 12
| const p = new HMPromise((resolve, reject) => { }) p.then(res => { console.log('res:', res) }).catch(err => { console.log('err:', err) }).finally(() => { console.log('finally') })
|
核心步骤:
- 参考文档:finally方法类似于调用
then(onFinally,onFinally),且不接受任何回调函数
- 注意:
- 版面问题,这里只保留函数部分的逻辑,其他代码未改动
- 后续未特殊说明,只保留函数部分代码
1 2 3
| finally(onFinally) { return this.then(onFinally,onFinally) }
|
面试回答:
手写Promise-实例方法finally
- 添加
finally方法,接收最终执行的回调函数onFinally
finally方法的本质为内部调用then方法
- 调用形式为第一个和第二个回调函数均传入
onFinally即可
1 2 3
| finally(onFinally) { return this.then(onFinally,onFinally) }
|
到目前已经将实例方法都实现啦
手写Promise-静态方法resolve
需求:
- 返回一个带有成功原因的
Promise对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| HMPromise.resolve(new HMPromise((resolve, reject) => { })).then(res => { console.log('res:', res) }, err => { console.log('err:', err) }) HMPromise.resolve('itheima').then(res => { console.log(res) })
|
核心步骤:
- 增加静态方法
resolve,根据传入的值返回不同的结果即可
1 2 3 4 5 6 7 8 9 10 11 12
| static resolve(value) { if (value instanceof HMPromise) { return value } return new HMPromise((resolve) => { resolve(value) }) }
|
面试回答:
手写Promise-静态方法resolve
通过static关键字添加静态方法resolve,接收参数value
内部判断传入的值
- 如果是
Promise实例,直接返回
- 其他的值,创建
Promise实例并返回,内部通过resolve(value)传递value
手写Promise-静态方法reject
需求:
- 返回一个带有拒绝原因的
Promise对象
1 2 3
| HMPromise.reject('error').catch(res => { console.log(res) })
|
核心步骤:
- 添加静态方法
- 返回
rejected状态的Promise
1 2 3 4 5 6 7
| static reject(value) { return new HMPromise((undefined, reject) => { reject(value) }) }
|
面试回答
手写Promise-静态方法reject
- 添加静态方法
reject并接收参数value
- 内部返回一个拒绝状态的
Promise实例即可
手写Promise-静态方法race
需求:
- 接收Promise数组,数组中第一个Promise敲定时,获取
成功/失败结果
- 传入的参数不是数组,直接报错

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| const p1 = new HMPromise((resolve, reject) => { setTimeout(() => { resolve(1) }, 2000) }) const p2 = new HMPromise((resolve, reject) => { setTimeout(() => { reject(2) }, 1000) }) HMPromise.race([p1, p2, 'itheima']).then((res) => { console.log('res:', res) }, err => { console.log('err:', err) })
|
核心步骤:
- 返回
Promise
- 判断是否未数组,不是直接报错
- 等待第一个敲定
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| static race(promises) { return new HMPromise((resolve, reject) => { if (!Array.isArray(promises)) { return reject(new TypeError('Argument is not iterable')) } promises.forEach(p => { HMPromise.resolve(p).then(res => { resolve(res) }, err => { reject(err) }) }) }) }
|
面试回答:
手写Promise-静态方法race
- 添加静态方法
race接收参数promises
- 内部返回一个新的
Promise实例,在返回的Promise实例中:
- 判断参数是否为数组,不是通过
reject传递错误
- 遍历Promise数组,通过
resolve静态方法等待每一个兑现
- 任何一个兑现,调用
resolve传递兑现结果
- 任何一个拒绝,调用
reject传递拒绝原因
手写Promise-静态方法all
需求:
- 接收Promise数组
- 所有Promise都成功时,返回一个成功的Promise对象及成功数组
- 任何一个Promise失败,返回一个失败的Promise对象及第一个失败原因
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| const p1 = HMPromise.resolve(1) const p2 = new HMPromise((resolve, reject) => { setTimeout(() => { resolve(2) }, 1000) }) const p3 = 3 HMPromise.all([p1, p2, p3]).then(res => { console.log('res:', res) }, err => { console.log('err:', err) })
|
核心步骤:
返回Promise
判断参数是否未数组:
- 不是:直接报错
是:
- 空数组直接兑现
- 处理全部兑现:记录结果->判断全部兑现
- 处理第一个拒绝
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| static all(promises) { return new HMPromise((resolve, reject) => { if (!Array.isArray(promises)) { return reject(new TypeError('Argument is not iterable')) } promises.length === 0 && resolve(promises) const results = [] let count = 0 promises.forEach((p, index) => { HMPromise.resolve(p).then(res => { results[index] = res count++ count === promises.length && resolve(results) }, err => { reject(err) }) }) }) }
|
面试回答:
手写Promise-静态方法all
- 添加静态方法
all
- 内部返回
Promise实例,在返回的Promise实例中:
- 判断参数是否为数组,不是通过
reject传递错误
- 空数组直接以空数组为结果进行兑现
- 遍历
Promise数组,通过resolve静态方法等待结果
- 处理全部兑现:
- 通过数组记录结果,用索引的方式来添加,目的是保证结果的顺序和
Promise数组的顺序一致
- 通过兑现次数进行判断,因为是通过索引的方式记录结果,如果第一次兑现的是最后一个,那么数组的长度就已经和Promise数组的长度一致了,所以需要通过兑现次数来进行判断
- 任意一个拒绝,调用
reject传递拒绝原因
手写Promise-静态方法allSettled
需求:-传送门
- 传入
Promise数组,当所有对象都已敲定时
- 返回一个新的
Promise对象及以数组形式保存的结果
1 2 3 4 5 6 7 8 9 10 11 12
| const p1 = HMPromise.resolve(1) const p2 = 2 const p3 = new HMPromise((resolve, reject) => { setTimeout(() => { reject(3) }, 1000) }) HMPromise.allSettled([p1, p2, p3]).then(res => { console.log('res:', res) }, err => { console.log('err:', err) })
|
核心步骤:
- 返回
Promise
- 判断是否为数组:
- 不是:报错
- 是:
- 空数组:直接兑现
- 等待全部敲定:并记录结果
- 处理兑现:
{state:FULFILLED,value:'xxx'}
- 处理拒绝:
{state:REJECTED,reason:'xxx'}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| static allSettled(promises) { return new HMPromise((resolve, reject) => { if (!Array.isArray(promises)) { return reject(new TypeError('Argument is not iterable')) } promises.length === 0 && resolve(promises)
const results = [] let count = 0 promises.forEach((p, index) => { HMPromise.resolve(p).then(res => { results[index] = { status: FULFILLED, value: res } count++ count === promises.length && resolve(results) }, err => { results[index] = { status: REJECTED, reason: err } count++ count === promises.length && resolve(results) }) }) }) }
|
面试回答:
手写Promise-静态方法allSettled
做法和all方法类似,区别是要获取全部敲定的结果(成功/拒绝),以及获取的结果是对象形式
添加静态方法allSettled
内部返回Promise实例,在返回的Promise实例中:
- 判断参数是否为数组,不是通过
reject传递错误
- 空数组直接以空数组为结果进行兑现
遍历Promise数组,通过resolve静态方法等待敲定结果
等待全部敲定:并记录结果,根据兑现和拒绝将如下格式的内容通过索引的方式的记录到数组中
处理兑现:{state:FULFILLED,value:'xxx'}
处理拒绝:{state:REJECTED,reason:'xxx'}
根据敲定的次数判断是否全部敲定,全部敲定之后,通过resolve传递结果数组
手写Promise-静态方法any
需求:-传送门
- 传入
Promise数组,
- 任何一个
Promise对象敲定时,返回一个新的Promise对象,及对应的结果
- 所有Promise都被拒绝时,返回一个包含所有拒绝原因的
AggregateError错误数组
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| const p1 = new HMPromise((resolve, reject) => { setTimeout(() => { reject(1) }, 2000) }) const p2 = 2 const p3 = new HMPromise((resolve, reject) => { setTimeout(() => { resolve(3) }, 1000) }) HMPromise.any([p1, p2, p3]).then(res => { console.log('res:', res) }, err => { console.dir(err) })
|
核心步骤:
- 返回Promise
- 判断是否为数组
- 不是:报错
- 是:
- 空数组:直接拒绝
- 等待结果:
- 第一个兑现
- 全部拒绝
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| static any(promises) { return new HMPromise((resolve, reject) => { if (!Array.isArray(promises)) { return reject(new TypeError('Argument is not iterable')) } promises.length === 0 && reject(new AggregateError(promises, 'All promises were rejected'))
const errors = [] let count = 0 promises.forEach((p, index) => { HMPromise.resolve(p).then(res => { resolve(res) }, err => { errors[index] = err count++ count === promises.length && reject(new AggregateError(errors, 'All promises were rejected')) }) }) }) }
|
面试回答:
手写Promise-静态方法any
做法和all方法也有点类似,区别是获取第一个兑现,或者是全部拒绝
- 添加静态方法
any
- 内部返回
Promise实例,在返回的Promise实例中:
- 判断参数是否为数组,不是通过
reject传递错误
- 空数组直接以空数组为结果进行兑现
- 遍历
Promise数组,通过resolve静态方法等待结果
- 第一个兑现,通过
resolve传递兑现结果
- 全部拒绝:
- 定义数组,保存拒绝原因,通过索引记录,目的是保证顺序和
Promise数组一致
- 通过次数判断是否全部拒绝,当全部拒绝时,通过
reject传递AggregateError类型的错误,并将拒绝原因数组传递进去即可
到目前已经将静态方法都实现啦
手写Promise-Promise\A+测试
接下来咱们来测试一下手写Promise的代码能否通过Promise\A+测试
Promise\A+规范:
Promise\A+是社区推出的规范,其实最早Promise也是社区推出并实现的,旨在规范Promise的实现,里面约定了:
- 状态必须是:pending,fulfilled,rejected
- then方法的详细实现细节
- ….
早期使用Promise可能需要导入一些库,比如:
现在已经不需要了,因为在ES6中已经加入语言标准,我们可以直接使用了:从 Chrome 32、Opera 19、Firefox 29、Safari 8 和 Microsoft Edge 开始,promises 是默认开启的。若要使缺乏完整 promise 实现的浏览器符合规范,或将 promise 添加到其他浏览器和 Node.js 中,请查看polyfill (2k gzipped)。
上面提到的库,以及ES6中实现的Promise,还有我们手写的Promise其实都是按照标准进行编写的,那么如何测试是否符合标准呢
测试:
社区提供了promises-aplus-tests用来测试实现的Promise是否符合规范,使用方式为:
使用CommonJS的方式暴露对象,要求如下
1 2 3 4
| 1. 提供deferred方法,返回对象{promise,resolve,reject} 1.1 promise: pending状态的promise实例(自己手写的Promise) 1.2 resolve: 以传入的原因兑现promise 1.3 reject: 以传入的原因拒绝promise
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| module.exports = { deferred() { const res = {} res.promise = new HMPromise((resolve, reject) => { res.resolve = resolve res.reject = reject }) return res } }
|
下包:
初始化项目: npm init -y
下包:npm i promises-aplus-tests -D
配置并执行命令:
package.json的scripts中加入
注: HMPromise是文件名,根据实际情况调整自己的文件名即可
1
| "test": "promises-aplus-tests HMPromise"
|
执行命令:npm run test
测试:
我们目前的写法中,没有考虑所有的边界情况,测试时会在2.3.3开始出错

只需要将resolvePromise函数替换为如下写法即可:
- 函数名,参数顺序和原函数一致
- 函数内部使用,序号+说明的方式对Promise\A+的标准进行标注
大伙可以参考注释对比确认还需要考虑哪些便捷情况,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| function resolvePromise(p2, x, resolve, reject) { if (x === p2) { throw new TypeError('Chaining cycle detected for promise'); }
if (x instanceof HMPromise) { x.then(y => { resolvePromise(p2, y, resolve, reject) }, reject); } else if (x !== null && ((typeof x === 'object' || (typeof x === 'function')))) { try { var then = x.then; } catch (e) { return reject(e); }
if (typeof then === 'function') { let called = false; try { then.call( x, y => { if (called) return; called = true; resolvePromise(p2, y, resolve, reject); }, r => { if (called) return; called = true; reject(r); } ) } catch (e) { if (called) return; called = true;
reject(e); } } else { resolve(x); } } else { return resolve(x); } }
|
替换完毕之后,再次执行npm run test,全部测试通过.

面试回答:
手写Promise-Promise\A+测试
Promise和Promise\A+规范的关系
Promise\A+是社区推出的规范,最早Promise也是社区推出并实现的,旨在规范Promise的实现,里面约定了:
- 状态必须是
pending,fulfilled,rejected
then方法的详细实现细节
- 各种边界情况….
早期使用Promise需要导入第三方库,现在在新式浏览器中已经不需要导入第三方库,因为Promise是默认开启的
无论是早期实现了Promise的第三方库,以及现在的新式浏览器内置的Promise,都是符合Promise\A+规范要求的
参考资料
- MDN-Promise
JS原理课-DAY03
函数柯里化
这一节咱们来学习函数柯里化,在计算机科学中,柯里化(英语:Currying),又译为卡瑞化或加里化,是把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数,并且返回接受余下的参数而且返回结果的新函数的技术。
这一节咱们会学习的有:
- 什么是函数柯里化
- 经典面试题
- 柯里化实际应用
柯里化 作为一种高阶技术, 可以提升函数的复用性和灵活性。
什么是函数柯里化
函数柯里化 (Currying) 是一种将多个参数的函数转换为单个参数函数的技术
转换完毕之后的函数:只传递函数的一部分参数来调用,让他返回一个新的函数去处理剩下的参数。
例子:
1 2 3 4 5 6 7
| function sum(num1, num2) { return num1 + num2 }
console.log(sum(1)(2))
|
核心步骤:
sum改为接收一个参数,返回一个新函数
- 新函数内部将参数1,参数2累加并返回
1 2 3 4 5
| function sum(num1) { return function (num2) { return num1 + num2 } }
|
面试回答:
什么是函数柯里化
- 函数柯里化是一种将多个参数的函数转换为单个参数函数的技术
- 转换完毕之后的函数只需要传递一部分参数进行调用,并且会返回一个新的函数去处理剩下的参数
柯里化面试题-全局变量
柯里化在面试的时候一般以笔试题出现,比如
需求:
1 2 3 4 5 6 7 8
| function sum(a, b, c, d, e) { return a + b + c + d + e }
|
核心步骤:
- 接收不定长参数
- 存储已传递的参数
- 判断长度
- 满足5:累加
- 不满足:继续返回函数本身
1 2 3 4 5 6 7 8 9
| let nums = [] function currySum(...args) { nums.push(...args) if (nums.length >= 5) { return nums.reduce((prev, curv) => prev + curv, 0) } else { return currySum } }
|
面试回答:
柯里化面试题-全局变量
- 定义数组保存参数
- 函数接收不定长参数
- 调用时将传入的参数,添加到数组中,并判断数组长度:
- 满足长度要求:累加并返回结果
- 未达到长度要求:继续返回函数本身
柯里化面试题-使用闭包
需求:
- 使用闭包将上一节代码中的全局变量,保护起来
- 支持自定义累加的参数个数
1 2 3 4 5 6 7 8
| function sumMaker(length){ }
const sum5 = sumMaker(5)
const sum7 = sumMaker(7) sum7(1,2,3)(4,5,6,7)
|
核心步骤:
- 定义外层函数:
- 定义参数
length
- 将全局变量迁移到函数内
- 定义内层函数:
- 参数长度判断,使用传入的参数
length
- 直接复用上一节的逻辑,并返回
1 2 3 4 5 6 7 8 9 10 11 12
| function sumMaker(length) { let nums = [] function inner(...args) { nums.push(...args) if (nums.length >= length) { return nums.reduce((prev, curv) => prev + curv, 0) } else { return inner } } return inner }
|
面试回答:
柯里化面试题-使用闭包
- 定义函数,接收参数,用来确定参数个数
- 内部将上一节的逻辑拷贝进去
- 返回原函数
- 通过这样的调整,可以让我们自定义参数的个数,并且没有上一节的全局变量数组
柯里化实际应用-类型判断
通过参数复用,实现一个类型判断生成器函数
需求:
- 将下列4个类型判断函数,改写为通过函数
typeOfTest动态生成
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| function isUndefined(thing) { return typeof thing === 'undefined' } function isNumber(thing) { return typeof thing === 'number' } function isString(thing) { return typeof thing === 'string' } function isFunction(thing) { return typeof thing === 'function' }
const typeOfTest =function(){
} const isUndefined = typeOfTest('undefined') const isNumber = typeOfTest('number') const isString = typeOfTest('string') const isFunction = typeOfTest('function')
isUndefined(undefined) isNumber('123') isString('memeda') isFunction(() => { })
|
核心步骤:
typeOfTest接收参数type用来接收判断的类型
- 内部返回新函数,接收需要判断的值,并基于
type进行判断
- 使用箭头函数改写为最简形式~~传送门-github
1 2 3 4 5
| const typeOfTest = (type) => { return (thing) => { return typeof thing === type } }
|
面试回答:
柯里化实际应用-类型判断
定义函数,接收需要判断的类型名
内部返回一个新的函数,
- 新函数接收需要判断的具体的值
- 新函数内部根据外层函数传入的类型,以及传入的值进行判断并返回结果
柯里化实际应用-固定参数
依旧是一个参数复用的实际应用
需求:
- 将如下3个请求的函数(都是post请求),变为通过
axiosPost函数动态生成
- 实现函数
axiosPost
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| axios({ url: 'url', method: 'get' }) axios({ url: 'url', method: 'get', params: { } }) axios({ url: 'url', method: 'post', data: '' }) axios({ url: 'url', method: 'post', data: '', headers: {
} })
requestWithMethod('get')({ url: '', params: {}, headers: {} }) requestWithMethod('post')({ url: '', headers: {}, data: {} })
|
核心步骤:
- 函数内部固定请求方法,post
- 函数内部调用
axios发请求即可
axios内部就是这样实现的
- 传送门-github:
1 2 3 4 5 6 7 8
| function requestWithMethod(method) { return (config) => { return axios({ method, ...config }) } }
|
面试回答:
柯里化实际应用-固定参数
函数柯里化是一种函数式编程思想:将多个参数的函数转换为单个参数函数,调用时返回新的函数接收剩余参数
常见面试题,将函数改写为如下调用新式:核心思想就是返回新的函数,根据已经记录的参数长度判断:
长度符合要求:累加
长度不符合要求:继续返回
1 2 3 4 5 6 7 8
| function sum(a, b, c, d, e) { return a + b + c + d + e }
|
常见应用:固定参数,比如axios中的:
- 类型判断函数
- get,post,put等别名方法
- 就用到了柯里化的思想
JS设计模式
这一节咱们来学习JS中的设计模式
传送门:wiki-设计模式
传送门:JavaScript设计模式与开发实践
设计模式的指的是:在面向对象软件设计过程中针对特定问题的简洁而优雅的解决方案。通俗一点说,设计模式就是给面向对象软件开发中的一些好的设计取个名字。
目前说到设计模式,一般指的是《设计模式:可复用面向对象软件的基础》一书中提到的23种常见的软件开发设计模式。
JavaScript中不需要生搬硬套这些模式,咱们结合实际前端开发中的具体应用场景,来看看有哪些常用的设计模式
这一节咱们会学习:
- JS中的常用设计模式
- 设计模式在开发/框架中的应用场景
工厂模式
在JavaScript中,工厂模式的表现形式就是一个直接调用即可返回新对象的函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| function Dog(name){ this.name=name } const dog = new Dog('柯基')
function ToyFactory(name,price){ return { name, price } } const toy1 = ToyFactory('布娃娃',10) const toy2 = ToyFactory('玩具车',15)
|
应用场景
Vue2->Vue3:
- 启用了
new Vue,改成了工厂函数createApp-传送门
- 任何全局改变 Vue 行为的 API(vue2) 现在都会移动到应用实例上(vue3)
- 就不会出现,Vue2中多个Vue实例共享,相同的全局设置,可以实现隔离
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| <!DOCTYPE html> <html lang="zh-CN">
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> #app1, #app2 { border: 1px solid #000; } </style> </head>
<body> <h2>vue2-全局注册组件</h2> <div id="app1"> 实例1 <my-title></my-title> </div> <div id="app2"> 实例2 <my-title></my-title> </div> <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.7.9/vue.js"></script> <script> Vue.component('my-title', { template: '<h2 style="color:orange">标题组件</h2>' }) const app1 = new Vue({ el: "#app1" })
const app2 = new Vue({ el: "#app2" })
</script> </body>
</html>
|
axios.create:
- 基于传入的配置创建一个新的
axios实例,传送门
- 项目中有2个请求基地址如何设置?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| const request1 = axios.create({ baseURL: "基地址1" }) const request2 = axios.create({ baseURL: "基地址2" }) const request3 = axios.create({ baseURL: "基地址3" })
request1({ url: '基地址1的接口' }) request2({ url: '基地址2的接口' }) request3({ url: '基地址3的接口' })
|
面试回答:
工厂模式:JS中的表现形式,返回新对象的函数(方法)
function sayHi(){} // 函数
const obj ={
name:'jack',
sayHello(){} // 方法
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| 2. 日常开发中,有2个很经典的场景
1. `vue3`中创建实例的api改为`createApp`,`vue2`中是`new Vue` 1. Vue3中,没有影响所有Vue实例的api了,全都变成了影响某个app对象的api,比如`Vue.component-->app.component` 2. `axios.create`基于传入的配置,创建一个新的请求对象,可以用来设置多个基地址
#### 单例模式
单例模式指的是,在使用这个模式时,单例对象整个系统需要保证**只有一个**存在。
**需求:**
1. 通过静态方法`getInstance`获取**唯一实例**
```javascript const s1 = SingleTon.getInstance() const s2 = SingleTon.getInstance() console.log(s1===s2)//true
|
核心步骤:
- 定义类
- 私有静态属性:
#instance
- 提供静态方法
getInstance:
- 调用时判断
#instance是否存在:
- 存在:直接返回
- 不存在:实例化,保存,并返回
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class SingleTon { constructor() { } static #instance
static getInstance() { if (SingleTon.#instance === undefined) { SingleTon.#instance = new SingleTon() } return SingleTon.#instance } }
|
实际应用:
- vant组件库中的弹框组件,保证弹框是单例
- toast组件:传送门
- notify组件:传送门
- 如果弹框对象
- 不存在,–>创建一个新的
- 存在,直接用
- vue中注册插件,用到了单例的思想(只能注册一次)
- vue2:传送门
- vue3:传送门
面试回答:
- 单例模式:
- 保证,应用程序中,某个对象,只能有一个
- 自己实现核心为一个返回唯一实例的方法,比如
getInstance
- 实例存在
->返回
- 实力不存在
->创建,保存->返回
- 应用场景:
vant的toast和notify组件都用到了单例:多次弹框,不会创建多个弹框,复用唯一的弹框对象
vue中注册插件,vue2和vue3都会判断插件是否已经注册,已注册,直接提示用户
观察者模式
在对象之间定义一个一对多的依赖,当一个对象状态改变的时候,所有依赖的对象都会自动收到通知。
举个例子:
dom事件绑定,比如
1 2 3 4 5 6 7 8 9
| window.addEventListener('load', () => { console.log('load触发1') }) window.addEventListener('load', () => { console.log('load触发2') }) window.addEventListener('load', () => { console.log('load触发3') })
|
- Vue中的watch:
面试回答:
- 观察者模式重点说清楚2点即可:
- 在对象之间定义一个一对多的依赖,当一个对象状态改变的时候,所有依赖的对象都会自动收到通知。
- 常见场景:vue中的watch,dom事件绑定
观察者模式和发布订阅模式的区别也是常见考点,回答方式见下一节
发布订阅模式01-应用场景
发布订阅模式可以实现的效果类似观察者模式,但是两者略有差异,一句话描述:一个有中间商(发布订阅模式)一个没中间商(观察者模式)

应用场景:
vue2中的EventBus:传送门
vue3中因为移除了实例上对应方法,可以使用替代方案:传送门
- 官方推荐,用插件
- 我们自己写
发布订阅模式02-自己写一个事件总线
需求:
1 2 3 4 5 6 7 8 9 10 11 12 13
| const bus = new HMEmitter()
bus.$on('事件名1',回调函数) bus.$on('事件名1',回调函数)
bus.$emit('事件名',参数1,...,参数n)
bus.$off('事件名')
bus.$once('事件名',回调函数)
|
核心步骤:
- 定义类
- 私有属性:
#handlers={事件1:[f1,f2],事件2:[f3,f4]}
- 实例方法:
- $on(事件名,回调函数):注册事件
- $emit(事件名,参数列表):触发事件
- $off(事件名):移除事件
- $once(事件名,回调函数):注册一次性事件
基础模板:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| <!DOCTYPE html> <html lang="zh-CN">
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head>
<body> <h2>自己实现事件总线</h2> <button class="on">注册事件</button> <button class="emit">触发事件</button> <button class="off">移除事件</button> <button class="once-on">一次性事件注册</button> <button class="once-emit">一次性事件触发</button> <script> class HMEmmiter { }
function qs(selector) { return document.querySelector(selector) } qs('.on').addEventListener('click', () => { }) qs('.emit').addEventListener('click', () => { }) qs('.off').addEventListener('click', () => { }) qs('.once-on').addEventListener('click', () => { }) qs('.once-emit').addEventListener('click', () => { }) </script> </body>
</html>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| class HMEmmiter { #handlers = {} $on(event, callback) { if (!this.#handlers[event]) { this.#handlers[event] = [] } this.#handlers[event].push(callback) } $emit(event, ...args) { const funcs = this.#handlers[event] || [] funcs.forEach(func => { func(...args) }) } $off(event) { this.#handlers[event] = undefined } $once(event, callback) { this.$on(event, (...args) => { callback(...args) this.$off(event) }) } }
|
面试回答:
- 发布订阅模式:可以实现的效果类似观察者模式,但是两者略有差异,一句话描述:一个有中间商(发布订阅模式)一个没中间商(观察者模式)
- 经典的场景是
vue2中的EventBus,vue3移除了实例的$on,$off,$emit方法,如果还需要使用:
- 使用第三方插件
- 自己实现事件总线:
- 自己实现事件总线的核心逻辑:
- 添加类,内部定义私有属性
#handlers={},以对象的形式来保存回调函数
- 添加实例方法:
$on:
- 接收事件名和回调函数
- 内部判断并将回调函数保存到
#handlers中,以{事件名:[回调函数1,回调函数2]}格式保存
$emit
- 接收事件名和回调函数参数
- 内部通过
#handlers获取保存的回调函数,如果获取不到设置为空数组[]
- 然后挨个调用回调函数即可
$off
- 接收事件名
- 将
#handlers中事件名对应的值设置为undefined即可
$once
- 接收事件名和回调函数
- 内部通过
$on注册回调函数,
- 内部调用
callback并通过$off移除注册的事件
原型模式
在原型模式下,当我们想要创建一个对象时,会先找到一个对象作为原型,然后通过克隆原型的方式来创建出一个与原型一样(共享一套数据/方法)的对象。在JavaScript中,Object.create就是实现原型模式的内置api
应用场景:
vue2中重写数组方法:
- 调用方法时(
push,pop,shift,unshift,splice,sort,reverse)可以触发视图更新:传送门
- 源代码:传送门
- 测试一下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| <!DOCTYPE html> <html lang="zh-CN">
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head>
<body> <h2>原型模式</h2> <div id="app"></div> <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.7.9/vue.js"></script> <script> const app = new Vue({ el: "#app", data: { foods: ['西瓜', '西葫芦', '西红柿'] } }) console.log(app.foods.push === Array.prototype.push) </script>
</body>
</html>
|
面试回答:
原型模式:
- 基于某个对象,创建一个新的对象
- JS中,通过
Object.create就是实现了这个模式的内置api
- 比如
vue2中重写数组方法就是这么做的
vue2中数组重写了7个方法,内部基于数组的原型Array.prototype创建了一个新对象
创建的方式是通过Object.create进行浅拷贝
重写的时候:
- 调用数组的原方法,获取结果并返回—方法的功能和之前一致
- 通知了所有的观察者去更新视图
1 2 3 4 5 6 7
| const app = new Vue({ el:"#app", data:{ arr:[1,2,3] } }) app.arr.push === Array.prototype.push
|
代理模式
代理模式指的是拦截和控制与目标对象的交互
这里我们来看一个非常经典的代理模式的应用: 缓存代理

核心语法:
- 创建对象缓存数据
- 获取数据时,先通过缓存判断:
- 有直接获取
- 没有:调用接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| const cache = {} async function searchCity(pname) { if (!cache[pname]) { const res = await axios({ url: 'http://hmajax.itheima.net/api/city', params: { pname } }) cache[pname] = res.data.list } return cache[pname] }
document.querySelector('.query').addEventListener('keyup', async function (e) { if (e.keyCode === 13) { const city = await searchCity(this.value) console.log(city) } })
|
面试回答:
- 代理模式的核心是,通过一个代理对象拦截对原对象的直接操纵
- 比如可以通过缓存代理:
- 缓存获取到的数据
- 拦截获取数据的请求:
- 已有缓存:直接返回缓存数据
- 没有缓存:去服务器获取数据并缓存
- 提升数据获取效率,降低服务器性能消耗
迭代器模式
迭代器模式提供一种方法顺序访问一个聚合对象中的各个元素,而又不暴露该对象的内部表示.简而言之就是:遍历
遍历作为日常开发中的高频操作,JavaScript中有大量的默认实现:比如
Array.prototype.forEach:遍历数组
NodeList.prototype.forEach:遍历dom,document.querySelectorAll
for in
for of
面试题:
for in 和for of 的区别?
for...in 语句以任意顺序迭代一个对象的除Symbol以外的可枚举属性,包括继承的可枚举属性。
- 对象默认的属性以及动态增加的属性都是可枚举属性
- 遍历出来的是属性名
- 继承而来的属性也会遍历
for...of语句在可迭代对象(包括 Array,Map,Set,String,TypedArray,arguments 对象等等)上创建一个迭代循环
- for of不会遍历继承而来的属性
- 遍历出来的是属性值
1 2 3 4 5 6 7 8 9 10
| Object.prototype.objFunc = function () { } Array.prototype.arrFunc = 'arrFunc'
const foods = ['西瓜', '西葫芦', '西兰花'] for (const key in foods) { console.log('for-in:key', key) } for (const iterator of foods) { console.log('for-of:iterator', iterator) }
|
可迭代协议和迭代器协议:
可迭代协议:传送门
- 给对象增加属方法
[Symbol.iterator](){}
- 返回一个符合迭代器协议的对象
迭代器协议:传送门
- next方法,返回对象:
{done:true},迭代结束
{done:false,value:'xx'},获取解析并接续迭代
- 实现方式:
- 手写
Generator
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
const obj = { [Symbol.iterator]() {
const arr = ['北京', '上海', '广州', '深圳'] let index = 0
return { next() { if (index < arr.length) { return { done: false, value: arr[index++] } } return { done: true } } }
} }
for (const iterator of obj) { console.log('iterator:', iterator) }
|
面试回答:
迭代器模式在js中有大量的默认实现,因为遍历或者说迭代时日常开发中的高频操作,比如forEach,for in,for of等
for in 和for of的区别:
for...in 语句以任意顺序迭代一个对象的除Symbol以外的可枚举属性,包括继承的可枚举属性。
- 对象默认的属性以及动态增加的属性都是可枚举属性
- 遍历出来的是属性名
- 继承而来的属性也会遍历
for...of语句在可迭代对象(包括 Array,Map,Set,String,TypedArray,arguments 对象等等)上创建一个迭代循环
- for of不会遍历继承而来的属性
- 遍历出来的是属性值
如何自定义可迭代对象?
- 需要符合2个协议:可迭代协议和迭代器协议,其实就是按照语法要求实现功能而已
- 可迭代协议:传送门
- 给对象增加属方法
[Symbol.iterator](){}
- 返回一个符合迭代器协议的对象
- 迭代器协议:传送门
- 有next方法的一个对象,内部根据不同情况返回对应结果:
{done:true},迭代结束
{done:false,value:'xx'},获取解析并接续迭代
- 实现方式:
- 自己手写实现逻辑
- 直接返回一个
Generator
参考资料
- 阮一峰-《ECMAScript 6 教程》
- 图灵社区-JavaScript高级程序设计
防抖和节流
防抖
防抖的适用场景
常见的前端性能优化方案 , 它可以防止JS高频渲染页面时出现的视觉抖动(卡顿):比如
- **示例1:**页面改变尺寸时,同步调整图表的大小
- **示例2:**输入内容时,结合ajax进行搜索并渲染结果
如果内容的渲染速度过快,都可能会造成抖动效果,并且连带会浪费性能
- 频繁执行逻辑代码,耗费浏览器性能
- 频繁发送请求去服务器,耗费服务器性能

适用场景:
- 在触发频率高的事件中
- 频率高的事件: resize、input 、scroll 、keyup….
- 执行耗费性能操作
- 需要实现的效果: 连续操作之后只有最后一次生效
这个时候就可以适用防抖来进行优化
手写防抖
防抖优化之后的效果可以通过一些具体的网站来进行确认,比如12306,他就是通过防抖进行的优化:

- 在输入内容的时候没有发送请求
- 输入完毕之后,稍等一会才发送请求去服务器
这个就是防抖的效果: 连续事件停止触发后,一段时间内没有再次触发,就执行业务代码
核心实现步骤
开启定时器,保存定时器id
清除已开启的定时器

那个输入框+搜索的例子优化之后代码如下:
1 2 3 4 5 6 7 8 9 10
| let timeId document.querySelector('.search-city').addEventListener('input', function () { clearTimeout(timeId) timeId = setTimeout(() => { renderCity(this.value) }, 500) })
|
lodash的debounce方法
实际开发中一般不需要手写防抖,因为已经有库里面提供了对应的方法,可以直接调用,也可以自己手写实现debounce,一会咱们就从这两个方面进行讲解:
lodash工具库中的debounce方法(常用)
debounce的实现原理(高频面试题)
传送门
1
| _.debounce(func, [wait=0], [options=])
|
参数
func (Function): 要防抖动的函数。
[wait=0] (number): 需要延迟的毫秒数。
[options=] (Object): 选项对象。
[options.leading=false] (boolean): 指定在延迟开始前调用。
[options.maxWait] (number): 设置 func 允许被延迟的最大值。
[options.trailing=true] (boolean): 指定在延迟结束后调用。
返回
(Function): 返回新的 debounced(防抖动)函数。
注意:
- 实际开发时一般给前2个参数即可,然后适用返回的函数替换原函数即可
- 项目中如果有
lodash那么直接使用它提供的debounce即可,不仅可以实现防抖,原函数中的this和参数均可以正常使用
手写debounce函数
手写实现debounce函数,实现lodash中debounce方法的核心功能
需求:
- 参数:
func (Function): 要防抖动的函数。
[wait=0] (number): 需要延迟的毫秒数。
- 返回值:
- (Function): 返回新的 debounced(防抖动)函数。
核心步骤:
返回防抖动的新函数
原函数中的this可以正常使用
原函数中的参数可以正常使用
1 2 3 4 5 6 7 8 9 10 11 12 13
| function debounce(func, wait = 0) { let timeId return function (...args) { let _this = this clearTimeout(timeId) timeId = setTimeout(function () { func.apply(_this, args) }, wait) } }
|
节流
节流的适用场景
常见的前端性能优化方案 , 它可以防止高频触发事件造成的性能浪费:比如
- 播放视频时同步缓存播放时间
- 如果要多设备同步,还需要通过
ajax提交到服务器
高频触发耗费性能的操作,会造成性能浪费

适用场景**:**在触发频率高的事件中, 执行耗费性能操作 , 连续触发 , 单位时间内只有一次生效
优化之前: 每当触发事件就会执行业务逻辑

**优化之后:**触发事件之后延迟执行逻辑,在逻辑执行完毕之后无法再次触发

手写节流
使用节流将播放器记录时间的例子优化:


核心步骤:
1.开启定时器,并保存 id
2.判断是否已开启定时器
3.定时器执行时 , id设置为空
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| let timeId video.addEventListener('timeupdate', function () { if (timeId !== undefined) { return }
timeId = setTimeout(() => { console.log('timeupdate触发') localStorage.setItem('currentTime', this.currentTime) timeId = undefined }, 3000)
})
|
lodash的throttle方法
实际开发中一般不需要手写节流,因为已经有库里面提供了对应的方法,可以直接调用,也可以自己手写实现throttle,一会咱们就从这两个方面进行讲解:
lodash工具库中的throttle方法(常用)
throttle的实现原理(高频面试题)
传送门
1
| _.throttle(func, [wait=0], [options=])
|
参数
func (Function): 要节流的函数。
[wait=0] (number): 需要节流的毫秒。
[options=] (Object): 选项对象。
[options.leading=true] (boolean): 指定调用在节流开始前。
[options.trailing=true] (boolean): 指定调用在节流结束后。
返回
(Function): 返回节流的函数。
注意:
- 实际开发时一般会给3个参数即可,然后适用返回的函数替换原函数即可
- 参数3:
options.leading=true默认为true,开始时触发节流函数,一般设置为false
- 项目中如果有
lodash那么直接使用它提供的throttle即可,不仅可以实现节流,原函数中的this和参数均可以正常使用
1 2 3 4 5 6 7 8 9 10
| const func = function (e) { console.log('timeupdate触发') console.log('e:', e) localStorage.setItem('currentTime', this.currentTime) }
const throttleFn = _.throttle(func, 1000, { leading: false })
video.addEventListener('timeupdate', throttleFn)
|
手写throttle方法
手写实现throttle函数,实现lodash中throttle方法的核心功能
需求:
- 参数:
func (Function): 要节流的函数。
[wait=0] (number): 需要节流的毫秒。
- 返回值:
- (Function): 返回节流的函数
核心步骤:
返回节流的新函数
原函数中的this可以正常使用
原函数中的参数可以正常使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| function throttle(func, wait = 0) { let timeId return function (...args) { if (timeId !== undefined) { return } const _this = this timeId = setTimeout(() => { func.apply(_this, args) timeId = undefined }, wait) } }
|