js面试必备:call、apply、bind的区别和实现

call、apply、bind都是改变this指向的方法

call和apply的区别:

用法:

let fn = function(a,b){
    console.log(this.name,a,b);//此时this指向fn1
}
let fn1={
	name:"zs"
}
fn.call(fn1,3,2)//zs 3 2
fn.apply(fn1,[3,2])//zs 3 2

由此可见,call和apply的作用差不多,区别在于call的和apply一个参数是分开传,一个是传数组

bind和其他两个的区别

用法:

let fn = function(a,b){
    console.log(this.name,a,b);
}
let fn1={
	name:"zs"
}
let result=fn.bind(fn1,2,3)
result()//zs 3 2

由此可见:bind的语法和call差不多,只是bind没有立即执行,而是等待执行。

手写call和apply:

1首先call是在原型上的方法使用Function.prototype
2call接收一个对象,和参数(apply是一个数组)
3给对象设一个fn属性与this绑定
4解构参数并调用
5删除该属性

Function.prototype.call1=function(context,...args){
	 context.fn=this
	 context.fn(...args)
	 delete context.fn
	}
Function.prototype.apply1=function(context,args){
 context.fn=this
 context.fn(...args)
 delete context.fn
}

手写bind

1、首先判断调用bind的是不是函数
2、获取this和bind时的参数
3、由于bind不是立即执行,所以返回的是一个函数,调用该函数可以额外增加参数。
4、连接两个参数

Function.prototype.bind1=function(context,...arg1){
		//只能函数调用bind
		if(typeof this !=="function"){
			throw new Error('Error')
		}
		let _this = this
		let arg1 = arg1
		return function (...arg2){
			return _this.apply(context,arg1.concat(arg2))
		}
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值