首页 > 编程语言 > 详细

JavaScript手写bind

时间:2021-05-06 15:19:19      阅读:27      评论:0      收藏:0      [点我收藏+]
// 模拟 bind
Function.prototype.bind1 = function () {
    // 使用arguments可以获取一个函数所有的参数
    // 使用Array.prototype.slice.call将参数拆解为数组
    const args = Array.prototype.slice.call(arguments)

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

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

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

function fn1(a, b, c) {
    console.log(‘this‘, this)
    console.log(a, b, c)
    return ‘this is fn1‘
}

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

 

JavaScript手写bind

原文:https://www.cnblogs.com/starlog/p/14734608.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!