call、apply及bind实现原理

38 阅读1分钟
Function.prototype.mycall = function(context = window,...args){
	//保存被调函数到context
	context.fn = this
	//执行函数
	let result = context.fn(...args)
	//删除
	delete context.fn
	return result
}
Function.prototype.myapply = function(context = window,args){
	context = context
	//保存被调函数到context
	context.fn = this
	//执行函数
	let result = context.fn(...args)
	//删除
	delete context.fn
	return result
}
Function.prototype.mybind = function(context,...args){
	var self = this//保存被调函数
	var fbound = function(...bindArgs){
		//执行被调函数
		return self.apply(
			//判断是不是new
			this instanceof self ? this : context,
			//参数合并
			args.concat(bindArgss)
		)
	}
	fbound.prototype = Object.create(self.prototype);
	//返回待执行函数
	return fbound
}