面试题之:js实现原生new, apply, bind,防抖,节流

503 阅读1分钟

基本为 前端面试中必考的题,可以着重理解与记忆。

1.实现new

Function.prototype.myNew = function() {
	const obj = new Object()
	const [Constro,...args] = [...arguments]
	obj.__proto__ = Constro.prototype
	const temp = Constro.apply(obj, args)
	return (temp && typeof temp == 'object') ? temp : obj
}

2. 实现apply

Function.prototype.myApply = function(context, array) {
	var _this = context || window
	var fn = Symbol()
	_this[fn] = this
	var result = array ? _this[fn]() : _this[fn](...array)
	delete _this[fn]
	return result
}

3. 实现bind

Function.prototype.myBind = function() {
	const [context, ...args] = [...arguments]
	if (typeof this !== 'function') {
    	throw new TypeError('error')
	}
	const _this = this
	return function Fn() {
		if (this instanceof Fn) {
			return new _this(...args, ...arguments)
		} else {
			_this.apply(context, [...args, ...arguments])
		}
	}
}

4. 防抖

function debounce(func,wait,immediate) {
    let timeout

    return function () {
        let context = this
        let args = arguments

        if (timeout) clearTimeout(timeout)
        if (immediate) {
            var callNow = !timeout
            timeout = setTimeout(() => {
                timeout = null
            }, wait)
            if (callNow) func.apply(context, args)
        } else {
            timeout = setTimeout(function(){
                func.apply(context, args)
            }, wait)
        }
    }
}

5. 节流

function throttles(fn, delay) {
	let timer = null
	let startTime = new Date()
	return function() {
		let currentTime = new Date()
		clearTimeout(timer)
		if (currentTime - startTime >= delay) {
			fn.apply(this, arguments)
			startTime = currentTime
		} else {
			timer = setTimeout(() =>{
				fn.apply(this, arguments)
			}, dalye)
		}
	}
}