关于javascript:js实现Functionprototypebind

Function.prototype.bind2 = function() {
    const args = Array.from(arguments)
    const context = args.shift() // context 在这个例子中指向 { x: 100 }
    const self = this // self 在这个例子中指向 fn1
    return function() {
        const argsAll = args.concat(Array.from(arguments))
        return self.apply(context, argsAll)
    }
}

function fn1(a, b, c) {
    console.log('this', this)
    console.log(a, b, c)
    return 'this is fn1'
}
const fn2 = fn1.bind2({ x: 100 }, 1)
const res = fn2(2, 3)
console.log(res)

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理