前端之模仿实现call、apply、bind的功能

202 阅读1分钟

在JavaScript中,call、apply、bind都有绑定函数执行上下文中this的能力,用法虽然有点差异,但核心的功能都是绑定执行上下文及执行函数内this的指向。

Function.prototype.myCall = function(obj, ...args){
        // obj为null、undefined时,绑定到window上
	if(obj == null) obj = window
	let type = typeof obj
        // 此处对下面几种基本类型进行包装,包装成对象
	if(type === 'string' || type === 'number' || type === 'boolean'){
		obj = new obj.constructor(obj)
	}
	// this为需要绑定this指向的函数 fn.call(obj) 该fn  将函数挂载在要绑定的对象上,通过该对象调用方法实现this指向的绑定
	obj.tempFn = this
        // 保存结果
	const res = obj.tempFn(...args)
        // 删除挂载在对象的函数属性
	delete obj.tempFn
        // 返回结果
	return res
}
// 下面apply和bind的实现原理是一样的
Function.prototype.myApply = function(obj, args){
	if(obj == null){
		obj = window
	}else{
		let type = typeof obj
		if(type === 'string' || type === 'number' || type === 'boolean'){
			obj = new obj.constructor(obj)
		}
	}
	
	obj.tempFn = this
	const res = obj.tempFn(...args)
	delete obj.tempFn
	return res
}

Function.prototype.myBind = function(obj){
	let that = this
	return function(...args){
		return that.myCall(obj, ...args)
	}
}