Pregunta

read the _.bind in source code, I didn't understand when the statement this instanceof bound will be true. Could anyone give an example.

_.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;
    };
  };
¿Fue útil?

Solución

For starters, Function.prototype.bind won't be defined. If bound is used as a constructor, (this instanceof bound) will be true. For example:

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

You can use the debugger to trace through this fiddle.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top