Function.prototype.bind

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 定义
Function.prototype.mybind=function(context){
context = context || window;
var args=[...arguments].slice(1)
const self = this
return function(...args2){
return self.apply(context,[...args,args2])
}
}

//使用

function fn(age,weight){
console.log(`我叫${this.name},年龄:${age},体重:${weight}`)
}
var zhangsan={name:'张三'}
var zsfn=fn.mybind(zhangsan,1,222)

zsfn()

防抖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const debounce = function(cb,timeout = 500,immediater = false){
if(cb && typeof cb == 'function'){
let timer = null;
let immediateSingal = immediate;
return function(){
if(timer){
clearTimeout(timer)
}
const _timeout = immediateSingal?0:timeout;
immediateSingal=false;
timer = setTimeout(cb,_timeout)
}
}else{
throw new Error('回调方法未传入或者并不是一个方法')
}
}

// 使用
var fn=function(){console.log('hi')}
var dfn = debounce(fn,3000,true)
dfn()

节流

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const throttle = function(cb,timeout = 500,immediate = true){
if(cb && typeof cb =='function'){
let timer;
let immediateSingal = immediate;
return function(){
if(timer){
return
}
const _timeout = immediateSingal?0:timeout;
immediateSingal=false;
timer = setTimeout(()=>{
cb();
timer = null;
},_timeout)
}
}else{
throw new Error('回调方法未传入或者并不是一个方法')
}
}