手写call,apply,bind的实现

48 阅读1分钟

手写call

方法步骤如下:

1.定义call方法

2.设置this并调用原函数

3.接收剩余参数并返回结果

// thisArg为传入this的对象
// this.原函数 (原函数.myCall)
Function.prototype.myCall=functon(thisArg,...args){
    // func.myCall(person,2,8)  this是func
     thisArg.f=this  //给 thisArg对象加了f属性
     const res= thisArg.f(...args)
     delete thisArg.f
     return res 
}
const person={
 name:"xyw",
}
function func(numA,numB){
    console.log(this)
    console.log(numA+numB);
    return numA + numB
}
const res= func.myCall(person,2,8)
console.log(res); 

使用Symbol优化

// thisArg为传入this的对象
// this.原函数 (原函数.myCall)Function.prototype.myCall=function(thisArg,...args){
    // func.myCall(person,2,8)  this是func
   
     const key = Symbol("key");
     thisArg[key]=this  //给 thisArg对象加了key属性
     const res= thisArg[key](...args)
     delete thisArg[key]
     return res 
}
const person={
 name:"xyw",
}
function func(numA,numB){
    console.log(this)
    console.log(numA+numB);
    return numA + numB
}
const res= func.myCall(person,2,8)
console.log(res); 
​

手写apply

// thisArg为传入this的对象
// this.原函数 (原函数.myCall)Function.prototype.myApply=function(thisArg,args){
    // func.myCall(person,2,8)  this是func
   
     const key = Symbol("key");
     thisArg[key]=this  //给 thisArg对象加了key属性
     const res= thisArg[key](...args)
     delete thisArg[key]
     return res 
}
const person={
 name:"xyw",
}
function func(numA,numB){
    console.log(this)
    console.log(numA+numB);
    return numA + numB
}
const res= func.myApply(person,[2,8])
console.log(res); 
​

手写bind

1.定义myBind方法

2 返回绑定的this新函数

3 合并绑定和新传入的参数

Function.prototype.myCall=function(thisArg,...args){
     const key = Symbol("key");
     thisArg[key]=this  
     const res= thisArg[key](...args)
     delete thisArg[key]
     return res 
}
​
Function.prototype.myBind=function(thisArg,...args){
    return (...resArg)=>{
        //此处的this是 func 
        return  this.myCall(thisArg,...args,...resArg)
     }  
}
​
const person={
 name:"xyw",
}
function func(numA,numB){
    console.log(this)
    console.log(numA+numB);
    return numA + numB
}
const res= func.myBind(person,2,8)
let num= res(2,8); 
console.log(num);