极简手写,再也不用担心面试官叫我手写了

462 阅读1分钟

来掘金有一段时间了。看过不少大佬发的贴子,关于手写的功能,是大同小异。用arguments这种不标准的关键词(当然也是为了更好的兼容)看着真的很难受。不要跟我说什么兼容性,ES6都是什么年代的产物了?为此本人尽可能做了极简的处理,看起来真的很爽,原来也就那么几行代码就搞定的感觉有没有?!!!

1.Object.create

function create(prototype) {
	function Fn() {}
	Fn.prototype = prototype
	return new Fn()
}

2.new

function myNew(fn,...args) {
	let obj=Object.create(fn.prototype)
	let res=fn.apply(obj,args)
	return res instanceof Object?res:obj
}

3.instanceof

function myInstanceof(left, right) {
	let l = left.__proto__
	let r = right.prototype
	while (l) {
		if (l === r) return true
		l = l.__proto__
	}
	return false
}

4.call

Function.prototype.myCall = function(that = globalThis, ...args) {
	that.fn = this
	let res = that.fn(...args)
	delete that.fn
    return res
}

5.apply

Function.prototype.myApply = function(that = globalThis, args = []) {
	that.fn = this
	let res = that.fn(...args)
	delete that.fn
    return res
}

6.bind

Function.prototype.myBind = function(that = globalThis, ...firstArg) {
	let fn = this
	function newFunc(...secArg) {
		let _this = this instanceof fn ? this : that
		return fn.apply(_this, firstArg.concat(secArg))
	}
	newFunc.prototype = Object.create(fn.prototype)
	return newFunc
}

7.深拷贝

function deepClone(obj, cache = new WeakMap()) {
	if (cache.has(obj)) return cache.get(obj)
	if (!obj && typeof obj !== 'object') return obj
	let res = new obj.constructor()
	cache.set(obj, res)
	for (let key in obj) {
		if (obj.hasOwnProperty(key)) {
			let val = obj[key]
			res[key] = typeof val === 'object' ? deepClone(val, cache) : val
		}
	}
	return res
}

8.防抖

function debounce(fn, wait) {
	let timer = null
	return function(...args) {
		clearTimeout(timer)
		timer = setTimeout(() => {
			fn.apply(this, args)
		}, wait)
	}
}

9.节流

function throttle(fn, wait) {
	let timer = null
	return function(...args) {
		if (timer) return
		timer = setTimeout(() => {
			fn.apply(this, args)
			timer = null
		}, wait)
	}
}

10.柯里化

function currying(fn, ...firstArg) {
	return function(...secArg) {
		let allArgs = firstArg.concat(secArg)
		if (allArgs.length < fn.length) return currying.call(null, fn, ...allArgs)
		return fn.apply(this, allArgs)
	}
}