最新公告
  • 欢迎您光临起源地模板网,本站秉承服务宗旨 履行“站长”责任,销售只是起点 服务永无止境!立即加入钻石VIP
  • bind的模拟

    正文概述 掘金(彬彬有礼5520)   2021-02-26   334

    bind

    ! 一句话介绍 bind:

    由此我们可以首先得出 bind 函数的两个特点:

     1.返回一个函数
     2.可以传入参数
    

    返回函数的模拟实现

    从第一个特点开始,我们举个例子:

    var foo = {
        value: 1
    };
    
    function bar() {
        console.log(this.value);
    }
    
    // 返回了一个函数
    var bindFoo = bar.bind(foo); 
    
    bindFoo(); // 1
    

    我们来写第一版的代码:

    // 第一版
    Function.prototype.bind2 = function (context) {
        var self = this;
        return function () {
            return self.apply(context);
        }
    }
    
    此外,之所以 return self.apply(context),是考虑到绑定函数可能是有返回值的,依然是这个例子:
    
    var foo = {
        value: 1
    };
    
    function bar() {
    	return this.value;
    }
    
    var bindFoo = bar.bind(foo);
    
    console.log(bindFoo()); // 1
    

    传参的模拟实现

    接下来看第二点,可以传入参数。
    
    这个就有点让人费解了,我在 bind 的时候,是否可以传参呢?
    
    我在执行 bind 返回的函数的时候,可不可以传参呢?
    
    让我们看个例子:
    
    var foo = {
        value: 1
    };
    
    function bar(name, age) {
        console.log(this.value);
        console.log(name);
        console.log(age);
    }
    
    var bindFoo = bar.bind(foo, 'daisy');
    bindFoo('18');
    
    // 1
    // daisy
    // 18
    
    函数需要传 name 和 age 两个参数,竟然还可以在 bind 的时候
    只传一个 name,在执行返回的函数的时候,再传另一个参数 age!
    
    这可咋办?不急,我们用 arguments 进行处理:
    

    第二版

    // 第二版
    Function.prototype.bind2 = function (context) {
        var self = this;
        
        // 获取bind2函数从第二个参数到最后一个参数
        var args = Array.prototype.slice.call(arguments, 1);
    
        return function () {
            // 这个时候的arguments是指bind返回的函数传入的参数
            var bindArgs = Array.prototype.slice.call(arguments);
            return self.apply(context, args.concat(bindArgs));
        }
    }
    

    构造函数效果的模拟实现

    完成了这两点,最难的部分到啦!因为 bind 还有一个特点,就是
    
    也就是说当 bind 返回的函数作为构造函数的时候,bind 时指定的 this 值会失效,但传入的参数依然生效。
    举个例子:
    
    var value = 2;
    
    var foo = {
        value: 1
    };
    
    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 obj = new bindFoo('18');
    // undefined
    // daisy
    // 18
    
    console.log(obj.habit); // shopping
    console.log(obj.friend); // kevin
    

    ! 注意:尽管在全局和 foo 中都声明了 value 值,最后依然返回了 undefind,说明绑定的 this 失效了,如果大家了解 new 的模拟实现,就会知道这个时候的 this 已经指向了 obj。

    所以我们可以通过修改返回的函数的原型来实现,让我们写一下
    

    第三版

    // 第三版
    Function.prototype.bind2 = function (context) {
        var self = this;
        var args = Array.prototype.slice.call(arguments, 1);
    
        var fBound = function () {
            var bindArgs = Array.prototype.slice.call(arguments);
            // 当作为构造函数时,this 指向实例,此时结果为 true,将绑定函数的 this 指向该实例,可以让实例获得来自绑定函数的值
            // 以上面的是 demo 为例,如果改成 `this instanceof fBound ? null : context`,实例只是一个空对象,将 null 改成 this ,实例会具有 habit 属性
            // 当作为普通函数时,this 指向 window,此时结果为 false,将绑定函数的 this 指向 context
            return self.apply(this instanceof fBound ? this : context, args.concat(bindArgs));
        }
        // 修改返回函数的 prototype 为绑定函数的 prototype,实例就可以继承绑定函数的原型中的值
        fBound.prototype = this.prototype;
        return fBound;
    }
    

    构造函数效果的优化实现

    但是在这个写法中,我们直接将 fBound.prototype = this.prototype
    
    我们直接修改 fBound.prototype 的时候,也会直接修改绑定函数的 prototype
    
    这个时候,我们可以通过一个空函数来进行中转:
    

    第四版

    // 第四版
    Function.prototype.bind2 = function (context) {
    
        var self = this;
        var args = Array.prototype.slice.call(arguments, 1);
    
        var fNOP = function () {};
    
        var fBound = function () {
            var bindArgs = Array.prototype.slice.call(arguments);
            return self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs));
        }
    
        fNOP.prototype = this.prototype;
        fBound.prototype = new fNOP();
        return fBound;
    }
    

    到此为止,大的问题都已经解决,给自己一个赞!o( ̄▽ ̄)d

    三个小问题

    1.apply 这段代码跟 MDN 上的稍有不同

    在 MDN 中文版讲 bind 的模拟实现时,apply 这里的代码是:

    self.apply(this instanceof self ? this : context || this, args.concat(bindArgs))
    

    多了一个关于 context 是否存在的判断,然而这个是错误的!

    举个例子:

    var value = 2;
    var foo = {
        value: 1,
        bar: bar.bind(null)
    };
    
    function bar() {
        console.log(this.value);
    }
    
    foo.bar() // 2
    
    以上代码正常情况下会打印 2,如果换成了 context || this,这段代码就会打印 1!
    
    所以这里不应该进行 context 的判断,大家查看 MDN 同样内容的英文版,就不存在这个判断!
    
    (2018年3月27日更新,中文版已经改了?)
    

    2.调用 bind 的不是函数咋办?

    不行,我们要报错!
    
    if (typeof this !== "function") {
      throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
    }
    

    3.我要在线上用

    那别忘了做个兼容:
    
    Function.prototype.bind = Function.prototype.bind || function () {
        ……
    };
    

    最终代码

    Function.prototype.bind2 = function (context) {
    
         //bind——试图被绑定的对象是不可调用的
        if (typeof this !== "function") {
          throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
        }
    
        var self = this;
        
         // 获取bind2函数从第二个参数到最后一个参数
        var args = Array.prototype.slice.call(arguments, 1);
    
         // 一个空函数来进行中转
        var fNOP = function () {};
    
        var fBound = function () {
         // 这个时候的arguments是指bind返回的函数传入的参数
            var bindArgs = Array.prototype.slice.call(arguments);
            
            //考虑到绑定函数可能是有返回值的
            return self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs));
        }
        
        // 修改返回函数的 prototype 为绑定函数的 prototype,实例就可以继承绑定函数的原型中的值
        fNOP.prototype = this.prototype;
        fBound.prototype = new fNOP();
        return fBound;
    }
    

    起源地下载网 » bind的模拟

    常见问题FAQ

    免费下载或者VIP会员专享资源能否直接商用?
    本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
    提示下载完但解压或打开不了?
    最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,若小于网盘提示的容量则是这个原因。这是浏览器下载的bug,建议用百度网盘软件或迅雷下载。若排除这种情况,可在对应资源底部留言,或 联络我们.。
    找不到素材资源介绍文章里的示例图片?
    对于PPT,KEY,Mockups,APP,网页模版等类型的素材,文章内用于介绍的图片通常并不包含在对应可供下载素材包内。这些相关商业图片需另外购买,且本站不负责(也没有办法)找到出处。 同样地一些字体文件也是这种情况,但部分素材会在素材包内有一份字体下载链接清单。
    模板不会安装或需要功能定制以及二次开发?
    请QQ联系我们

    发表评论

    还没有评论,快来抢沙发吧!

    如需帝国cms功能定制以及二次开发请联系我们

    联系作者

    请选择支付方式

    ×
    迅虎支付宝
    迅虎微信
    支付宝当面付
    余额支付
    ×
    微信扫码支付 0 元