手写bind函数

51 阅读1分钟

手写bind函数

function fun(a,b,c){
            console.log(this)
            console.log(a,b,c)
            return "hello bind"
        }
        // let cd = fun.bind({x:'10'},'李','家','城')
        // console.log(cd())

        Function.prototype.myBind = function(){
            const thts = this
            const arr = Array.prototype.slice.call(arguments)
            const _this = arr.shift()
            return function(){ 
                return thts.apply(_this,arr)
            }
        }

        let cd = fun.myBind({x:'10'},'李','嘉','城')
        console.log(cd())

重点

  1. Array.prototype.slice.call(arguments)给arguments变成真正的数组
  2. Function.prototype.myBind