关于javascript:手写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

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理