手寫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
相關文章
相關標籤/搜索