前端面试题整理——手写bind函数

    var arr = [1,2,3,4,5]
    console.log(arr.slice(1,4))
    console.log(arr)


    Function.prototype.bind1 = function(){
        // arguments是个列表不是数组,将参数拆解为数组
        const args = Array.prototype.slice.call(arguments)
        // 获取this(数组第一项),shift方法是删除第一项返回第一项值
        const t = args.shift()
        // fn1.bind(...)中的fn1
        const self = this
        //返回一个函数
        return function(){
            return self.apply(t,args)
        }

    }

    function fn(a,b){
        console.log(this)
        console.log(a,b)
        return 'ok'
    }
    const fn2 = fn.bind1({x:100},10,20)
    console.log(fn2())

考点:

使用闭包和理解作用域

放弃安逸,持续努力——成长
原文地址:https://www.cnblogs.com/MarsPGY/p/13461881.html