IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    理解 JavaScript 中的 Function.prototype.bind

    admin发表于 2016-06-08 03:22:35
    love 0

    .bind()创建了一个函数,当这个函数在被调用的时候,它的 this 关键词会被设置成被传入的值(这里指调用bind()时传入的参数)。

    修改前:

    var myObj = {
     
        specialFunction: function () {
     
        },
     
        anotherSpecialFunction: function () {
     
        },
     
        getAsyncData: function (cb) {
            cb();
        },
     
        render: function () {
            var that = this;
            this.getAsyncData(function () {
                that.specialFunction();
                that.anotherSpecialFunction();
            });
        }
    };
     
    myObj.render();

    修改后:

    var myObj = {
     
        specialFunction: function () {
     
        },
     
        anotherSpecialFunction: function () {
     
        },
     
        getAsyncData: function (cb) {
            cb();
        },
     
        render: function () {
            var that = this;
            this.getAsyncData(function () {
                this.specialFunction();
                this.anotherSpecialFunction();
            }.bind(this));
        }
    };
     
    myObj.render();

    浏览器支持:
    Function.prototype.bind 在IE8及以下的版本中不被支持

    幸运的是,Mozilla Developer Network(很棒的资源库),为没有自身实现 .bind() 方法的浏览器提供了一个绝对可靠的替代方案:

    if (!Function.prototype.bind) {
      Function.prototype.bind = function(oThis) {
        if (typeof this !== 'function') {
          // closest thing possible to the ECMAScript 5
          // internal IsCallable function
          throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
        }
     
        var aArgs   = Array.prototype.slice.call(arguments, 1),
            fToBind = this,
            fNOP    = function() {},
            fBound  = function() {
              return fToBind.apply(this instanceof fNOP
                     ? this
                     : oThis,
                     aArgs.concat(Array.prototype.slice.call(arguments)));
            };
     
        if (this.prototype) {
          // Function.prototype doesn't have a prototype property
          fNOP.prototype = this.prototype; 
        }
        fBound.prototype = new fNOP();
     
        return fBound;
      };
    }

    摘自:http://blog.jobbole.com/58032/


    © admin for 可乐吧, 2016. | Permalink | No comment | Add to del.icio.us
    Post tags: bind() 方法

    您可能也喜欢:
    Javascript的prototype与constructor
    JavaScript库解构
    JavaScript 对象(Object)学习(二)
    JavaScript注释语法
    无觅

    Feed enhanced by Better Feed from Ozh



沪ICP备19023445号-2号
友情链接