防抖
function throttle(fun, time) {
let timer = null
return () => {
if (timer) {
return
}
fun()
timer = setTimeout(() => {
timer = null
}, time)
}
}
节流
function debounce(fun, time) {
let timer = null
return () => {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fun()
}, time)
}
}
深拷贝
function deepClone(a, cache) {
let res = undefined
if (!cache) {
cache = new Map()
}
if (a instanceof Object) {
if (cache.get(a)) {
return cache.get(a)
}
if (a instanceof Function) {
if (a.prototype) {
res = (...args) => {
return a.call(this, ...args)
}
} else {
res = (...args) => {
return a.call(undefined, ...args)
}
}
} else if (a instanceof Array) {
res = []
} else if (a instanceof Date) {
res = new Date(a - 0)
} else if (a instanceof RegExp) {
res = new RegExp(a)
} else {
res = {}
}
cache.set(a, res)
for (let k in a) {
if (a.hasOwonProperty(k)) {
res[k] = deepClone(a[k])
}
}
return res
} else {
res = a
}
}
手写 instanceof
function _instanceof(a, b) {
if (typeof a !== 'object' || a === null) {
return false
}
let proto = Object.getPrototypeOf(a)
while (true) {
if (proto === null) {
return false
}
if (proto === b.prototype) {
return true
}
proto = Object.getPrototypeOf(proto)
}
}
手写 new
function _new(fn, ...args) {
let o = Object.create(fn.prototype)
let res = fn.apply(o, args)
return typeof res === 'object' ? res : o
}
数组去重
// 1. set
function distDoWeight(arr) {
return Array.from(new Set(arr))
}
标签:instanceof,cache,return,复习,res,JavaScript,timer,let,手写
From: https://www.cnblogs.com/cqkjxxxx/p/16612208.html