常用函数实现

new

1
2
3
4
5
6
function new(con, ...args) {
let obj = Object.create({})
obj.__proto__ = con.prototype
let res = con.apply(obj, args)
return typeof res === 'object' ? res : obj
}

instanceof

1
2
3
4
5
6
7
8
9
function instanceof(a, b) {
while(a.__proto__) {
if (a.__proto__ === b.prototype) {
return true
}
a = a.__proto__
}
return false
}

防抖

1
2
3
4
5
6
7
8
9
10
11
function debounce(fn, wait) {
let timer = null
return function(...args) {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fn.apply(this, args)
}, wait)
}
}

节流

1
2
3
function throttle(fn, wait) {
}

call

apply

bind

深拷贝

1
2
3
4
5
6
7
8
9
10
11
12
// 递归
function deepClone(obj) {
if(!obj || typeof obj != 'object') return obj
if(obj instanceof RegExp) return new RegExp(obj)
var cloneObj = new obj.constructor
for(let key in obj) {
if (obj.hasOwnProperty(key)) {
cloneObj[key] = deepClone(obj[key])
}
}
return cloneObj
}