今日复习计划:设计模式 、weekMap。
一. 前端知识
1. 设计模式
1.1 装饰器
function setName(target){
target.name = 'decorate'
}
@setName
class Person{}
console.log(Person.name) // 'decorate'
当然@setName的用法需要你安装babel-plugin-transform-decorators-legacy,这里就不多加赘述了。 装饰器模式常用场景:
- 高阶函数
- redux的connect
1.2 迭代器模式
迭代器模式值提供一种方法可以顺序访问对象中的元素。在ES6中内置的for of即为迭代器模式。
let obj = {
name: 'cxm',
age: 22
}
for(let key of obj){
console.log(obj[key])
}
1.3 观察者
VUE的数据响应核心设计模式。
class Observer {
constructor(value) {
this.value = value;
this.update = () => {
console.log(this.value + "update something");
};
}
}
class Subject {
constructor() {
this.observerList = [];
}
addObserver(observer) {
this.observerList.push(observer);
}
notify() {
this.observerList.forEach((observer) => observer.update());
}
}
const subject = new Subject();
const dom1 = new Observer("dom1");
const dom2 = new Observer("dom2");
subject.addObserver(dom1);
subject.addObserver(dom2);
subject.notify();
1.4 工厂模式
class User {
constructor(name, author) {
this.name = name;
this.author = author;
}
static getInstance(role) {
switch (role) {
case "admin":
return new User("管理员", [1, 2, 3]);
case "empoyee":
return new User("员工", [1]);
}
}
}
let admin = new User("管理员", [1, 2, 3]);
console.log(admin);
let normalUser = User.getInstance("empoyee");
console.log(normalUser);
简单工厂使用场景:
- 数据类型较少
- 创建逻辑简单
- 通过一个参数即可创建正确对象
1.5 单例模式
let User = (function () {
let instance;
return function (name) {
if (instance) {
return instance;
}
this.name = name;
instance = this;
};
})();
let a = new User("xiaoming");
let b = new User("xiaohong");
console.log(a);
console.log(b);
场景
- 引用第三方库(多次引用只会使用一个库引用,如 jQuery)
- 弹窗(登录框,信息提升框)
- 购物车 (一个用户只有一个购物车)
- 全局态管理 store (Vuex / Redux)
优缺点
- 优点:适用于单一对象,只生成一个对象实例,避免频繁创建和销毁实例,减少内存占用。
- 缺点:不适用动态扩展对象,或需创建多个相似对象的场景。
2. weekMap
let map = new Map();
map.set(
{
a: 1,
},
1
);
map = null;
上述代码中,map = null,map正确的被回收了,而{a: 1}则不会,由此产生了内存泄漏。weekMap则可以解决这类问题。weekMap对引用型数据的引用为弱引用,当进行标记清除的回收时,并不会考虑到weekMap的引用,所以不会产生内存泄漏问题。
二. 算法
最近一直在刷算法题,因为要考华为的机考以及数字马力的机考。
三. 面经
1. 华为机考
3道算法题,2道easy1道medium。最终踩着及格线过了。
四. 其他
经历了一个很不好的面试体验,过程就不多赘述了。突然觉得前公司要求面试官经过培训考核后才能进行面试的流程挺好的,毕竟一个不专业的面试官真的很糟糕。
He said, one day you’ll leave this world behind,
so live a life you will remenber