javascript基础 -- 手写bind

bind()的作用与call()和apply()一样,都是可以改变函数运行时上下文,区别是call()和apply()在调用函数之后会立即执行,而bind()方法调用并改变函数运行时上下文后,返回一个新的函数,供我们需要时再调用

因此可以考虑用apply来实现bind的功能,直接上代码

Function.prototype.bind = function (that) {
        if (typeof this !== 'function') { // 判断调用bind方法的对象的类型是否为函数
            throw new TypeError('only function can use bind');
        }

        var args = [].slice.call(arguments, 1); // 调用bind传递进来的参数,除去第一个参数obj test.bind(obj, pram)
        var fToBind = this;
        var fNop = function() {}; // 用来复制this的原型
        var fBound = function () {
            // this instanceof fBound ? this : that 主要是为了适应 new fBound()时,this指向自身实例
            // 这也是为什么使用bind后,再new得到的函数,原先绑定的对象会失效
            // args.concat([].slice(arguments)) args 为调用bind时传入的参数,arguments 为执行 fBound传入的参数,然后拼接在一起
            /*  举个栗子
                this.a = 20;
                var o = {
                    foo: function() {
                        console.log(111);
                        console.log(this.a);
                    },
                    bar(){ // ES6的写法,包含箭头函数都有这个问题
                        console.log(222);
                    }
                }

                var f = o.foo.bind({a: 30});
                new f(); // 111   undefined => new 对bind失效,导致this不为{a: 30},而是foo{}
            */
            return fToBind.apply(this instanceof fBound ? this : that, args.concat([].slice(arguments)));
        }

        fNop.prototype = this.prototype;// 继承原函数的原型,这里不直接fBound.prototype = this.prototype,是为了避免两个原型指向同一个对象,相互影响
        fBound.prototype = new fNop();// 利用中介函数实现原型的继承

        return fBound;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值