1.如何实现一个 new
function _new(fn, ...arg) {
let obj = Object.create()
obj.__proto__ = fn.prototype
let res = fn.apply(obj, arg)
return res instanceof Object ? res : obj
}
2.如何实现一个 call
function myCall(obj) {
obj.__proto__._xx = this;
var res = obj._xx(...Array.from(arguments));
delete obj.__proto__._xx;
return res;
}
3.如何实现一个 apply
function myApply(obj, params) {
obj.__proto__._xx = this;
var res =obj._xx(...params);
delete obj.__proto__._xx;
return res
}
4.如何实现一个 bind
function myBind(obj) {
var firstParams = []
for (var i = 1
firstParams.push(arguments[i])
}
var _self = this
return function () {
var lastParams = []
for (var i = 0
lastParams.push(arguments[i])
}
obj.__proto__._xx = _self
obj._xx(...firstParams, ...lastParams)
delete obj.__proto__._xx
}
}
5.如何实现一个深拷贝
function deepClone(obj) {
let type = Object.prototype.toString.call(obj).slice(8, -1)
let _new = null
if (type === 'Array') {
_new = []
obj.forEach((item) => {
_new.push(item)
})
} else if (type === 'Object') {
_new = {}
for (let key in obj) {
_new[key] = deepClone(obj[key])
}
} else {
return obj
}
return _new
}
6.如何实现一个函数防抖
function debounce(fn, wait){
let timer = null
return function(){
let args = arguments
clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, args)
}, wait)
}
}
7.如何实现一个函数节流