分享

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

 丹枫无迹 2021-09-27
    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())

考点:

使用闭包和理解作用域

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多