美文网首页
手写bind函数

手写bind函数

作者: 木羽木羽女口生 | 来源:发表于2020-12-04 01:49 被阅读0次
function fn1(a,b,c){
    console.log('this',this)
    console.log(a,b,c)
    return 'this is fn1'
}

const fn2 = fn1.bind({x:100},10,20,30)
const res = fn2
console.log(res)

//模拟 bind
Function.prototype.bind1 = function(){
    //将参数拆解为数组
    const args = Array.prototype.slice.call(arguments)

    //获取this(数组第一项)
    const t = args.slice()

    //fn1.bind(...)中的fn1
    const self = this

    //返回一个函数
    return function(){
        return self.apply(t,args)
    }
}

相关文章

网友评论

      本文标题:手写bind函数

      本文链接:https://www.haomeiwen.com/subject/pyhbwktx.html