手写bind函数

Function.prototype.bind1 = function(){
        //1.将参数变为数组
        let args = Array.prototype.slice.call(arguments)
        //2.拿到数组的第一项做为this,已经剩余项
        let t = args.shift();  //此时t为第一项,且args里面的第一项已经剔除掉了
        //3.这里的this即调用的时候fn1.bind()的fn1
        let self = this
        //返回一个函数,且函数有返回值
        return function(){
            return self.apply(t, args)
        }
    }
    
    let fn1 = function(a, b, c){
        console.log('this:', this)
        console.log(a, b, c)
        return 'this is fn1'
    }
    const fn2 = fn1.bind1({x: 100}, 10, 20, 30)
    const res = fn2()
    console.log(res)
    //this: {x: 100}
    //10 20 30
    //this is fn1
相关文章
相关标签/搜索