(面试)原生实现call,bind,apply改变this指向
var obj={
name:'卢本伟'
}
function func(){
console.log(this.name)
}
func.call(obj)
我们都知道,this指向问题, 函数谁调用,this就指向调用者
我们实现的思路就可以是给函数上创建一个方法并且添加到函数都有的prototype上
Function.prototype.callcodewhy = function (target, ...arg) {
//永远记着谁调用就指向谁
target.fn = this
// 主动调用传进来的形参,绑定this
target.fn(...arg)
// 使用完后删除
delete target.fn(...arg)
}
使用
func.callcodewhy(obj)
我们实现了一个call方法后,bind和apply都是大同小异
apply 和 call 的主要区别就在 apply是接收一个数组
Function.prototype.applycodewhy = function (target, arg=[]) {
//接收数组
if(arg && !arg instanceof Array){
// 我们就可以告诉调用者传参是错误的
throw('apply方法的形参必须是一个数组')
}
//永远记着谁调用就指向谁
target.fn = this
// 主动调用传进来的形参,绑定this
target.fn(...arg)
// 使用完后删除
delete target.fn(...arg)
}
bind方法的区别在于,它返回的是一个方法,需要再次调用,因此在开发中使用频率较高
Function.prototype.bindcodewhy = function (target, ...arg) {
// 使用箭头函数,传递this
return (...arg2)=>{
//拼接bind再次调用的参数
let arg3=arg+arg2
target.fn = this
// 主动调用传进来的形参,绑定this
target.fn(...arg3)
// 使用完后删除
delete target.fn(...arg3)
}
}
使用
let binds= func.bindcodewhy(obj)
binds(1)