_.bind下划线的源代码

时间:2014-04-28 12:47:58

标签: javascript underscore.js

在源代码中阅读_.bind,我不明白语句this instanceof bound何时为真。任何人都可以举个例子。

_.bind = function(func, context) {
    var args, bound;
    if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
    if (!_.isFunction(func)) throw new TypeError;
    args = slice.call(arguments, 2);
    return bound = function() {
      if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
      ctor.prototype = func.prototype;
      var self = new ctor;
      ctor.prototype = null;
      var result = func.apply(self, args.concat(slice.call(arguments)));
      if (Object(result) === result) return result;
      return self;
    };
  };

1 个答案:

答案 0 :(得分:4)

对于初学者,将不会定义Function.prototype.bind。如果bound用作构造函数,(this instanceof bound)将为true。例如:

Function.prototype.bind = null;
var Constructor = function () {};
var BoundConstructor = _.bind(Constructor, {});
var b = new BoundConstructor();  // (this instanceof bound) === true

您可以使用调试器来追踪this fiddle