前端手写题整理(一):函数与设计模式
Joyer Lee Lv3

把早期积攒在手写题仓库里的题目整理成系列发出来,这一篇覆盖函数工具与设计模式:防抖节流、深拷贝、发布订阅、观察者模式。每道题保留当时的实现思路,适合面试前快速过一遍。

防抖与节流

两者都是为了减少函数的调用频率:

  • 防抖(debounce):短时间内多次触发同一事件,只执行最后一次——把频繁触发的函数延迟处理
  • 节流(throttle):一定时间窗口内只触发一次
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 debounce(fn, delay) {
let timer = null;

return function (...args) {
if (timer) {
clearTimeout(timer);
}

timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}

function throttle(fn, delay) {
let timer = null;

return function (...args) {
if (timer) {
return;
}

timer = setTimeout(() => {
fn.apply(this, args);
timer = null;
}, delay);
};
}

典型应用:防抖用于搜索框输入、窗口 resize;节流用于滚动监听、按钮防连点。

深拷贝

难点在循环引用和特殊对象(Date、RegExp、不可枚举属性)。用 WeakMap 记录已拷贝对象解决循环引用,用 Object.getOwnPropertyDescriptors 保留属性描述符:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const isComplexDataType = (obj) =>
(typeof obj === 'object' || typeof obj === 'function') && obj !== null;

const deepClone = function (obj, hash = new WeakMap()) {
if (obj.constructor === Date) return new Date(obj);
if (obj.constructor === RegExp) return new RegExp(obj);
if (hash.has(obj)) return hash.get(obj); // 循环引用直接返回缓存
let allDesc = Object.getOwnPropertyDescriptors(obj);
let cloneObj = Object.create(Object.getPrototypeOf(obj), allDesc); // 继承原型链
hash.set(obj, cloneObj);
for (let key of Reflect.ownKeys(obj)) {
cloneObj[key] =
isComplexDataType(obj[key]) && typeof obj[key] !== 'function'
? deepClone(obj[key], hash)
: obj[key];
}
return cloneObj;
};

验证时可以构造一个含循环引用的对象:obj.loop = obj,拷贝后修改 cloneObj.arr 不会影响原对象即通过。

发布订阅模式

与观察者的区别:发布订阅有一个事件中心(调度中心)解耦发布者和订阅者,双方互不感知;观察者模式中主题直接持有观察者引用。

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
const pubsub = {
subscribers: {},

subscribe: function (eventName, callback) {
if (!this.subscribers[eventName]) {
this.subscribers[eventName] = [];
}
this.subscribers[eventName].push(callback);
},

unsubscribe: function (eventName, callback) {
if (this.subscribers[eventName]) {
const index = this.subscribers[eventName].indexOf(callback);
if (index !== -1) {
this.subscribers[eventName].splice(index, 1);
}
}
},

publish: function (eventName, data) {
if (this.subscribers[eventName]) {
this.subscribers[eventName].forEach((callback) => {
callback(data);
});
}
},
};

前端里的典型落地:EventBus、Vue 早期的事件总线、消息通知中心。

观察者模式

主题(Subject)维护观察者列表,状态变化时统一通知:

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 Subject {
constructor() {
this.observers = [];
}

addObserver(observer) {
this.observers.push(observer);
}

removeObserver(observer) {
const index = this.observers.indexOf(observer);
if (index > -1) {
this.observers.splice(index, 1);
}
}

notifyAll() {
this.observers.forEach((observer) => {
observer.update();
});
}
}

class Observer {
update() {
console.log('Observer updated');
}
}

系列下一篇整理数组与字符串类手写题。