好久没开工 闲着挺无聊 工作不如意 手写练习题
防抖、节流
防抖
function debounce (fn, delay){
let timer;
return function(){
if(timer){
clearTimeout(timer);
}
const args =arguments
setTimeout(() => {
fn.apply(this, args);
}, delay)
}
}
节流
function throttle(fn, delay){
let flag = true;
return function(){
if(!flag)return;
flag = false;
const args = arguments;
setTimeout(() => {
fn.apply(this, args);
flag = true;
},delay)
}
}
call、apply
call
Function.prototype.call2 = function (argus){
const args = argus || window
args.func = this;
let argsT = [];
for(let i =1,leng = arguments.length; i< leng; i++){
argsT.push("arguments[" + i + "]");
}
const res = eval("args.func(" +argsT +")");
delete args.func
return res
}
xdm我学完es6了 我改一下。。。
Function.prototype.call2 = function (argus){
const args = argus || window
args.func = this;
let argsT = [...arguments].slice(1);
const res = args.func(...argsT)
delete args.func
return res
}
apply
Function.prototype.apply2 = function (argus, array){
const args = argus || window
args.func = this;
let res;
let argsT = [];
if(!array){
res = args.func()
}else {
for(let i = 0, leng = arguments.length; i< leng; i++){
argsT.push("arguments[" + i + "]");
}
res = eval("args.func(" +argsT +")");
}
delete args.func
return res
}
参考文章
掘金
知乎
zhuanlan.zhihu.com/p/261332524
思否
本文只是自己练习着玩 以上大佬们的文章都有详细的讲解 如有不懂的可以去详看
写的过程有一点点自己的思考 摸清大佬们的思路 整合多种想法 再去考虑用什么新的方式去重写 (虽然并没有 是个缝合怪)
萌新的文章 有错误希望各位大佬指正 二胖在此谢过各位