前端analysis | 3w & 1h

《前端面试》- 前端知识体系重点

2020-11-25

JS

Javascript ES6

Event Loop

执行异步,会创建微任务或者宏任务,添加到对应的队列中等待处理

环境:从左到右执行 同步 微任务队列 宏任务
浏览器 console之类的 promise.then 等 setTimeout,setInterval等逐个执行
node 11- console之类的 nextTrick → promise.then其他的 先(Timer阶段)setTimout,setInterval全部执行完毕→ I/o → Check → Close循环完毕
node(11) 11+ console之类的 nextTrick → promise.then其他的 先(Timer阶段)setTimout,setInterval逐个执行→ 跳转微任务在继续下个宏任务

验证code,

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
console.log(1);
setTimeout(() => {
console.log(2);
process.nextTick(() => {
console.log(3);
});
new Promise((resolve) => {
console.log(4);
resolve();
}).then(() => {
console.log(5);
});
});
new Promise((resolve) => {
console.log(7);
resolve();
}).then(() => {
console.log(8);
});
process.nextTick(() => {
console.log(6);
});
setTimeout(() => {
console.log(9);
process.nextTick(() => {
console.log(10);
});
new Promise((resolve) => {
console.log(11);
resolve();
}).then(() => {
console.log(12);
});
});

node <11:1 7 6 8 2 4 9 11 3 10 5 12
node>=11:1 7 6 8 2 4 3 5 9 11 10 12

缓存策略

强制缓存 http1.0

Expire – 绝对时间

  • 缺点: 客户端、服务器时间不同,则无效

Cache-control – 相对时间

  • fix上述问题,根据客户端时间设置
  • 但是,必须等缓存过期,不能提前知道服务端内容改变了,

协商缓存 http1.1

Last-modidied/Last-modified-since

  • 根据linux文件最后修改的时间,提前知道文件修改
  • 但是如果文件都是动态生成,每次都是重新创建,那么久无效

Etag/If-None-Match

  • fix上述问题,就根据文件内容hash是否修改

Http code

200

success

301

Moved Permanently to the URL

302

temporarily moved to the URL

304

no modified

400

Bad Request

401

Unauthorized

403

forbidden

404

not found

500

server error

502

server gateway error

ES6 Proxy

防抖与节流

防抖

避免多次点击,界面抖动,延迟,取最后一次动作

1
2
3
4
5
6
7
8
9
function boundce(func,wait){
return function(){
const ctx = this;
clearTimout(timer);
const timer = setTimeout(
func.apply(ctx,args)
,wait)
}
}

节流

固定的时间内,发生多次,只有一次成功

1
2
3
4
5
6
7
8
9
10
function throttle(func,wait){
let previous ;
return function(){
const ctx = this;
if(Date.now() - preview > wait){
func.apply(ctx,args)
previous = Date.now();
}
}
}

macro Task 与microTask

事件循环中的异步队列有两种:macro(宏任务)队列和 micro(微任务)队列。宏任务队列可以有多个,微任务队列只有一个。

常见的 macro-task 比如:setTimeout、setInterval、 setImmediate、script(整体代码)、 I/O 操作、UI 渲染等。
常见的 micro-task 比如: process.nextTick、new Promise().then(回调)、MutationObserver(html5 新特性) 等。

先执行宏任务,一次一个,执行完毕,执行所有的microTask,没有则继续执行宏任务

1
2
3
4
5
6
7
8
9
for (const macroTask of macroTaskQueue) {
//逐个处理
handleMacroTask();
//批次处理
for (const microTask of microTaskQueue) {
handleMicroTask(microTask);
}
}

new Person 执行过程

先继承Person.prototype创建对象{}
设置this指向{}
设置属性,
没有特殊返回,直接返回this

拦截Person,只能new

new.target

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 之前做法
function Person(name){
if(this instance Of Person){
this.name = name
}else{
throw new Error('')
}
}

//new.target
function Person(name){
if(typeof new.target !== 'undefined'){
// if(typeof new.target === Persion){}
this.name = name;
}
}

CSS

Css重点

参考

宏任务和微任务

使用支付宝打赏
使用微信打赏

若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏