手写 call apply bind

// 定义一个 show 方法
        function show(...args) {
            console.log(this);
        }
        // 原型上新增一个 myCall 方法
        Function.prototype.myCall = function (ctx, ...args) {
            // console.log(this);//此时 this 指向 show 方法
            ctx.fn = this//把 show 方法赋值给 ctx 上的一个属性 fn 方法
            ctx.fn(...args)//调用 fn 方法,对象上方法,谁调用 this 指向谁,所以此时 this 指向 ctx,就是传入进来的新对象 {name:'zs'}
            delete ctx.fn//删除该属性
        }
        // 调用 myCall 方法并传入一个新的对象
        //  call 方法传参方式:
        //                  参数1:对象
        //                  参数2,参数3.......:多个属性一一传值
        show.myCall({ name: 'zs' }, '参数1', '参数2', '参数3')



        // 原型上新增一个 myApply 方法
        Function.prototype.myApply = function (ctx, args) {
            if (args && !(args instanceof Array)) throw ('myApply方法只接受数组作为参数')
            ctx.fn = this
            ctx.fn(args)
            delete ctx.fn
        }
            //  apply 方法传参方式:
            //               参数1:对象
            //               参数2:数组(多个属性作为数组的成员项)
        show.myApply({ name: 'zs' }, ['参数1', '参数2', '参数3'])



        // 原型上新增一个 bind 方法
        Function.prototype.myBind = function (ctx, ...args1) { 
            // bind 返回一个新的函数,需要再次调用
            return (...args2)=>{
                ctx.fn=this
                ctx.fn(...args1.concat(args2))
                delete ctx.fn
            }
        }
            //  bind 方法传参方式:
            //               参数1:对象
            //               参数2,参数3.......:多个属性一一传值
            //
        const bind=show.myBind({ name: 'zs' }, '参数1', '参数2', '参数3')
        // bind 返回一个新的函数,需要再次调用
        bind('参数4')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值