1. call 和 apply 办法
call 办法用于扭转函数的 this 指向;
let objD = {name: '小李'}
let obj = {
age: 7,
showDetail: function () {console.log('my name:' + this.name)
}
}
obj.showDetail()
应用 call 办法当前,扭转 this 的指向,前面的参数为失常函数参数;
let objD = {name: '小李'}
let obj = {
age: 7,
showDetail: function (age) {console.log('my name:' + this.name + ',my age:' + age)
}
}
obj.showDetail.call(objD, 17)
用 apply 能够实现雷同的成果,只是参数要改成数组的模式;
let objD = {name: '小李'}
let obj = {
age: 7,
showDetail: function (age) {console.log('my name:' + this.name + ',my age:' + age)
}
}
obj.showDetail.apply(objD, [16])
2. 手写防抖
防抖是闭包的一个利用,timer 能够被外界批改,又不会净化全局;
function debounce(fn, delay) {
let timer
return function (...args) {
// 前面再点击就会销毁第一次的初始化,再 delay 之内就会始终循环这个过程而办法不执行
if (timer) {clearTimeout(timer)
}
// 第一次点击初始化
timer = setTimeout(() => {fn.apply(this, args)
}, delay)
}
}
3. reduce + hash 去重排序
const initData = (ydrz) => {let hash = {};
ydrz = ydrz.reduce((pre, cur) => {hash[cur.czdz] ? '' : (hash[cur.czdz] = true && pre.push(cur));
return pre;
}, []);
let result = ydrz.sort((a, b) => a.czdz - b.czdz);
return result;
};