call、bind、apply区别用法以及实现

call、bind、apply都是改变当前this指向的问题,但各自有各自的区别

call

call函数接收两个多个参数,第一个是当前this的指向是水,其他的就是为改变指向的方法所传的参数。修改当前指向的时候也会执行对应的函数

	function add(a,b){
		...
	}
	add.call(this,2,3);//2指add中参数a,3指的是参数b;这里的this应该是window
call的实现
Function.prototype.call=function(content=window){
	content.fn=this;
	let args=[...arguments].slice(1);
	let result=content.fn(...args);
	delete content.fn
	return result
}

apply

apply也call相似,但apply接收的是一个数组;

function add(a,b){
	...
}
add.apply(this,[1,2])
apply的实现
Function.protptype.apply=function(content=window){
	content.fn=this;
	let result;
	if(argments[1]){
		result=content.fn(...argmengts[1])
	}else{
		result=content.fn();
	}
	delete content.fn;
	return result
}

bind

会创建一个新函数。当这个新函数被调用时,bind() 的第一个参数将作为它运行时的 this,之后的一序列参数将会在传递的实参前传入作为它的参数。(来自于 MDN )

function add(a,b){
	...
}
var Add=add.bind(this,[1,2])
bind的实现
Function.protype.bind=function(content){
	if(content instanceof Function){
		let _this=this;
		let args=[...arguments].slice(1);
		return function Fn(){
			if(this instanceof Fn){
				return _this.apply(this,args.concat([...arguments]))
			}
			return _this.apply(content,args.concat([...arguments]))
		}
	}else{
		throw Error('not a function')
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值