JavaScript手写bind函数

函数是有Function构建出来的,它本身是内有bind函数的。我们不能影响原有的bind,需要重新在原型上定义一个bind

一、首先在Function.prototype写个custBind函数,它有二个参数,一个用来接收this,一个用rest参数来接收剩余所有的参数

Function.prototype.customBind = function (context, ...bindArgs) {
            console.log('bindArgs--', bindArgs);
}          

二、bind,call,apply这些方法它第一个参数是要对this重新绑定的对象,所以要把第一个参数取出来。再返回新的函数,并且这个新的函数也是可以接受参数的(原有的bind调用之后生成的新函数也是可以接收参数的),把二次接受的参数用concat拼接再调用apply函数。

function fn(a, b, c) {
    console.log('参数', a, b, c);
}
//bind函数
Function.prototype.customBind = function (context, ...bindArgs) {
    let self = this;
    return function (...args) {
        const newArr = bindArgs.concat(args);
        return self.apply(context,newArr)
    }
}
let fn1 = fn.customBind({ x: 100 }, 10)
console.log(fn1(20,30));

同理call,apply也可以按相同思路来写

posted @ 2021-04-10 00:40  雪旭  阅读(578)  评论(0编辑  收藏  举报