JavaScript-bind函数的简单实现

bind() 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。

Function.prototype.myBind = function (thisArg, ...argsArray) {
    //第一步,对thisArg处理,以防传进来的不是对象,基本类型的数据会转为包装对象,null和undefined会指向window
    thisArg = thisArg ? Object(thisArg) : window
    let fn = this
    //第二步, 返回的结果为一个函数
    function proxyFn(...args) {
        //第三步,调用绑定的函数, 这里的this就是这个函数
        thisArg.fn = fn
        //第四步,比较特殊,对两个传入的参数进行合并
        let finalArgs = [...argsArray, ...args]
        //第五步,返回调用函数的结果
        let result = thisArg.fn(...finalArgs)
        delete thisArg.fn
        return result
    }
    //第六步,返回该函数
    return proxyFn
}
//测试案例1
function foo() {
    console.log('foo函数被调用', this); //foo函数被调用 String {'abc', fn: ƒ}
}
foo.myBind("abc")()

//测试案例2
function sum(num1, num2, num3, num4) {
    console.log(num1, num2, num3, num4, this) //10 20 40 50 String {'abc', fn: ƒ}
    return num1 + num2 + num3 + num4
}
let res = sum.myBind('abc', 10, 20)
let result = res(40, 50)
console.log(result);//120
//简写版本
Function.prototype.myBind = function (thisArg, ...argsArray) {
    thisArg = thisArg ? Object(thisArg) : window
    thisArg.fn = this
    return function (...newArgs) {
        var args = [...argsArray, ...newArgs]
        return thisArg.fn(...args)
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值