实现 bind 方法

//  bind 实现
    //  1.返回一个函数 
    //  2.除了第一个this外 后面接收一堆参数
    //  3.改变this的函数可以执行new方法

    Function.prototype.bindTwo = function(that, ...arg) {
        let _this = this;

        function bindFn(...arg2) {
            // 判断是否执行了 new 方法 this instanceof bindFn;
            // 如果没有new  this 指向 window
            // arg2 有可能在new的时候传入参数
            // arg 和 arg2 只是为了接收参数
            return _this.call(this instanceof bindFn ? this : that, ...arg, ...arg2)
        }
        // 加一个中转函数 避免修改
        function bindNullFn(){};
        // 继承执行函数的原型
        bindNullFn.prototype = this.prototype;
        bindFn.prototype = new bindNullFn();

        return bindFn;
    }

    var foo = {
        value: 1
    };

    // 第一步 简单实现
    // function bar(name) {
    //     console.log(this.value, `name:${name}`)
    // }

    // var bindFoo = bar.bind(foo, 2);
    // var bindFoo2 = bar.bindTwo(foo, 3);
    // bindFoo();
    // bindFoo2();

    // 第二步 实现 new
    function bar(name, age) {
        this.habit = 'shopping';
        console.log(this.value);
        console.log(name);
        console.log(age);
    }

    bar.prototype.friend = 'kevin';

    var bindFoo = bar.bind(foo, 'daisy');
    var bindFoo2 = bar.bindTwo(foo, 'daisy');

    var obj = new bindFoo('18');
    var obj2 = new bindFoo2('18');
    // undefined
    // daisy
    // 18
    // console.log(obj.habit);
    // console.log(obj.friend);
    // shopping
    // kevin

看了 这个链接的 https://github.com/mqyqingfeng/Blog/issues/12 的bind 实现 自己实现了一个。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值