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))
}
}