underscore 1.7 _.bind函数源码疑惑


这几天在阅读underscore的源码,看到函数方法的时候,遇到一点问题。请大家,帮个忙啦~

underscore 1.7 bind函数源码


 javascript


 _.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('Bind must be called on a function');
    args = slice.call(arguments, 2);
    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 (_.isObject(result)) return result;
      return self;
    };
    return bound;
  };

问题

实际使用时,哪一种情况会跳过下面的if判断,执行后面的代码?能否举个实例?


 javascript


 if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));

underscore JavaScript

帕琪的红茶 9 years, 2 months ago

正常情况下不应该都会跳过的么?这个问题可以简化下面这段代码:


 bound = function() {
    return this instanceof bound;
}

在什么情况下会返回 true 在什么情况下会返回 false 。这个代码一看就可以知道,只要是正常的调用,诸如 bound() 之类,函数内部的 this 肯定是其它对象的。但是当 new bound 这种调用的时候,内部指针的对象就发生变化了,指向 bound 了,这个时候就会返回 true 了。

爨冏雠蠡鬯蕤 answered 9 years, 2 months ago

作为构造函数调用的情况下,以下是一个简化了的版本,可以直接在console里执行查看


 var _ = {};
_.bind = function(func, context) {
    var args, bound;
    args = [].slice.call(arguments, 2);
    bound = function() {
      if (!(this instanceof bound)) return func.apply(context, args.concat([].slice.call(arguments)));
      console.log('skip');
      return self;
    };
    return bound;
  };
var f = function() {};
var bf = _.bind(f, {});
bf();
new bf();

这个问题本质是对JS函数调用中this的理解

早安G组 answered 9 years, 2 months ago

Your Answer