防抖节流
function debounce(fun,time){
let timer;
return function (...args){
clearTimeout(timer);
timer = setTimeout(()=>{
fun.apply(this,...args);
},time);
}
}
document.getElementById('buttonOne').addEventListener('click', debounce(()=>{console.log(1)},1000));
function throttle(fun,time){
let tLast = 0;
return function (...args){
let tNow = new Date();
if (tNow - tLast > time){
fun.apply(this,...args);
tLast = tNow;
}
}
}
function throttleT(fun,time){
let isSend;
let timer;
return function (...args){
if (isSend || isSend === undefined){
fun.apply(this,args)
isSend = false;
timer = setTimeout(()=>{
isSend = true;
},time)
}
}
}
document.getElementById('buttonTow').addEventListener('click',throttle(()=>{console.log(1)},1000));
柯里化
function kerRui (fn,...args){
if (typeof fn !== "function") return new Error('fn is not a function');
return function (...NewArgs){
if ([...args,...NewArgs].length !== fn.length){
return kerRui.call(this,fn,...args,...NewArgs);
}else{
return fn.apply(this,[...args,...NewArgs]);
}
}
}
通过箭头函数来简化this指向问题
let kerRui = (fn,...args) => {
return args.length === fn.length
? fn(...args)
: (...argsT)=> kerRui(fn,...args,...argsT)//箭头函数不跟函数体就是直接返回对应的东西
// : (...argsT)=> {return kerRui(fn,...args,...argsT)}
}
instanceof
function myInstanceof(obj,isProto){
if (typeof obj !== 'object' || !obj ){
return new Error('first argument is not a object');
}
let proto = Object.getPrototypeOf(obj);
while (true){
if (proto === null) return false;
if (proto === isProto.prototype) return true;
proto = Object.getPrototypeOf(proto);
}
}
深拷贝
递归拷贝青春版
function deepCopy (obj){
if (typeof obj === 'object'){
let res = obj instanceof Array?[]:{};
for (const i in obj){
res[i] = deepCopy(obj[i]);
}
return res;
}else{
return obj;
}
}
递归拷贝防循环引用+while循环优化数组+通用函数抽象版,没有实现拷贝函数
function myForEach(obj,fun){
let i = -1;
let isArr = Array.isArray(obj);
let keys = isArr?false:Object.keys(obj);
let len = keys.length || obj.length;
while (++i < len){
let key = isArr?i:keys[i];
let value = obj[key];
fun(value,key);
}
return obj;
}
function deepCopy(obj,map = new Map()){
if (typeof obj === 'object' && obj !==null ){
if (map.get(obj)){
return map.get(obj);
}
let res = Array.isArray(obj)?[]:{};
map.set(obj,res);//先加入后操作
myForEach(obj,(value,key)=>{
res[key] = deepCopy(value,map);
})
return res;
}else {
return obj;
}
}