zoukankan      html  css  js  c++  java
  • 手写Function.bind函数

    if(!Function.prototype.bind){

      Function.prototype.bind = function(oThis){

        if(typeof this !=="function"){ //如果不函数抛出异常

          throw new TyperError("")

        }

        var aArgs = Array.prototype.slice.call(arguments,1),   //此处的aArgs是除函数外的参数

          fToBind = this,                  //要绑定的对象

          fNOP = function(){},

          fBound = function(){

            return fToBind.apply(

              this instanceof fNOP ? this:oThis||this,aArgs.concat(Array.prototype.slice.call(arguments)));

              )

          };

        fNOP.prototype = this.prototype;

        fBound.prototype = new fNOP();

        return  fBound;

      }

    }

    明白 bind 的用法就必须要知道 apply 的用法,MDN 指出,apply 是直接修改了函数内部的指向到第一个参数,并将第二个参数数组传参进函数并运行这个函数。也就是说

    var obj = {test: function() { console.log(this, arguments) }},
        func = obj.test;
    
    obj.test("Hello", ",", "world", "!");
    func.apply(obj, ["Hello", ",", "world", "!"]);
    

    这两种运行方式是一样的。那么回到 Polyfill 中发现参数的写法是 args.concat(slice.call(arguments))args 是将 bind时候定义的除第一个参数外的其它参数,而此时的 arguments 是指函数调用时候的参数,通过数组的操作将这两个参数合并成一个数组传入函数内部。看个例子你可能更容易明白:

    /** 代码接上 **/
    var newFunc = func.bind(obj, "Hello", ",");
    newFunc("world", "!");
    

    那么再来回答问题一,这个是典型的属性继承的方法,本来使用

    bound.prototype = self.prototype
    

    就可以将原属性集成过来了,但是这样两个对象属性都指向同一个地方,修改 bound.prototype 将会造成 self.prototype也发生改变,这样并不是我们的本意。所以通过一个空函数 nop 做中转,能有效的防止这种情况的发生。

    bind返回的是函数

    if (!Function.prototype.bind) {
        Function.prototype.bind = function(obj) {
            var _self = this
                ,args = arguments;
            return function() {
                _self.apply(obj, Array.prototype.slice.call(args, 1));
            }
        }
    }
  • 相关阅读:
    NOIP201208同余方程
    NOIP模拟赛 最佳组合
    NOIP模拟赛 拓展
    CF1253E Antenna Coverage(DP)
    LOJ6033「雅礼集训 2017 Day2」棋盘游戏 (博弈论,二分图,匈牙利算法)
    CF582E Boolean Function(DP,状态压缩,FMT)
    CF750G New Year and Binary Tree Paths(DP)
    Codeforces Round 596 题解
    AGC008E Next or Nextnext(组合计数,神奇思路)
    ARC082E ConvexScore(神奇思路)
  • 原文地址:https://www.cnblogs.com/myzy/p/5228239.html
Copyright © 2011-2022 走看看