Skip to main content

One post tagged with "call"

View All Tags

· 2 min read
Lvxl

防抖

连续触发事件但是在设定的一段时间内中 只执行最后一次 场景:

  • 搜索框输入
  • 文本编辑器实时保存
function debounce(fn,wait = 2000, open=true) {
let timer;
let isUse = false;
return function(...arg) {
if (timer) {
clearInterval(timer)
}
if (open && !isUse) {
fn.call(this,...arg)
isUse = true
}
timer = setTimeout(() => {
fn.call(this,...arg)
}, wait);
}
}

节流

连续触发事件但是在设定的一段时间内 只执行一次 场景:

  • 高频事件 快速点击, 鼠标滑动, resize事件, scroll事件
  • 下拉加载
function throttle(fn, wait=200) {
let now = Date.now()
return function(...arg) {
let curtime = Date.now()
if(curtime - now > wait) {
fn.call(this,...arg)
now = Date.now()
}
}
}

call,apply,bind

改变this指向

// call
// obj.say._call(a, 'xxx')
// this谁调用指向谁 => target[symbolkey] = this
// this = f() say
Function.prototype._call = function(target, ...args) {
target = target || window
const symbolKey = Symbol()
target[symbolKey] = this
const res = target[symbolKey](...args)
delete target[symbolKey]
return res
}

Function.prototype._apply = function(target, args) {
target = target || window
let symbolkey = Symbol()
target[symbolkey] = this
const res = target[symbolkey](...args)
delete target[symbolkey]
return res
}

Function.prototype._bind = function(target, ...args) {
target = target || {}
const symbolkey = Symbol()
target[symbolkey] = this
return function (...outerArgs) {
const res = target[symbolkey](...args,...outerArgs)
return res
}
}