前端积累 | 手写Function.prototype.bind()

106 阅读1分钟

这个函数是函数对象上的一个方法,能够返回一个新的函数,使其绑定的this指向传入的第一个参数。而后续的参数则为函数本身的参数,并会在函数调用的时候被优先使用。

const obj ={
    val: 1,
    getVal(x,y){
        return `${this.val},${x},${y}`;
    }
}
const getVal1 = obj.getVal;
const getVal2 = getVal1.bind(obj,2)
getVal1(2);// undefined,2,undefined
getVal2(3);// 1,2,3

实现思路

既然我们想要一个改了this的新函数,那么我们只需要返回一个修改过this的函数即可,那么使用apply就是不错的选择。

  1. 获取函数本身,此时的this就是函数本身
  2. 返回一个指向了新的this的新函数

代码示例

const obj ={
    val: 1,
    getVal(x,y){
        return `${this.val},${x},${y}`;
    }
}
Function.prototype.myBind = function (asThis, ...args){
    const fn = this;
    return function(...args2){
        return fn.apply(asThis,[args,args2]);
    };
}
const getVal1 = obj.getVal;
const getVal2 = getVal1.myBind(obj,2)
getVal1(2);// undefined,2,undefined
getVal2(3);// 1,2,3

属性对应

原生的bind是通过创建一个绑定函数实现的,绑定函数拥有下面几个内部属性。

  • BoundTargetFunction,需要被包装的函数,也就是手写中的fn
  • BoundThis,我们想要绑定的this,也即asThis
  • BoundArguments,函数传入的优先参数列表,也即args
  • Call,调用时被运行,结构为Call(BoundThis,BoundArguments)