练练手写代码能力
面试题:
手写防抖函数
- 内部使用闭包缓存所要做的事件
function debounce(fn, delay) {
if(typeof fn !== 'function') {
return new TypeError('fn不是函数');
}
let timer; // 唯一一个timer值
return function() {
var _this = this; // 当前的this 是debounce 的this
var args = arguments;
if(timer) {
clearTimeout(timer);
}
timer = setTimeout(function() {
fn.apply(_this, args); // 用apply指向调用debounce的对象,相当于_this.fn(args);
}, delay);
}
}
button.addEventListener('click', debounce(() => {
console.log('value')
}), 600)
手写深拷贝
- 使用递归方式
let oldObj = {
id: 1,
name: '测试',
msg: {
text: '手写深拷贝'
}
}
let newObj = {}
function deepCopy(newObj, oldObj) {
for (const k in oldObj) {
let item = oldObj[k];
// 判断当前是数组或是对象,使用递归当前函数
if(item instanceof Array) {
newObj[k] = [];
deepCopy(newObj[k], item)
} else if(item instanceof Object){
newObj[k] = {};
deepCopy(newObj[k], item); //
} else { // 简单的数据类型,直接赋值
newObj[k] = item;
}
}
}
deepCopy(newObj, oldObj);
console.log(newObj); //{ id: 1, name: '测试', msg: { text: '手写深拷贝' } }
newObj.name = '新的数据';
console.log(newObj); //{ id: 1, name: '新的数据', msg: { text: '手写深拷贝' } }
console.log(oldObj); //{ id: 1, name: '测试', msg: { text: '手写深拷贝' } }