关于javascript:手写bind函数

0次阅读

共计 446 个字符,预计需要花费 2 分钟才能阅读完成。

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
正文完
 0