首页 > underscore 1.7 _.bind函数源码疑惑

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判断,执行后面的代码?能否举个实例?

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

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

var _ = {};
var slice = Array.prototype.slice;
var Ctor = function(){};

 _.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');
      Ctor.prototype = func.prototype;
      var self = new Ctor;
      Ctor.prototype = null;
      var result = func.apply(self, args.concat(slice.call(arguments)));
      if ((typeof result) === 'object') return result;
      return self;
    };
    return bound;
  };
var f = function() {};
var bf = _.bind(f, {});
bf(); // 一般调用
new bf(); // 构造函数调用,输出"skip",并返回一个对象

这个问题本质是对JS函数调用中this的理解,JS函数调用时this有四种情况:
一般直接调用f()时,this为Global Object,在浏览器中时window对象;
作为对象属性调用obj.f()时,this为所调用的对象obj;
作为构造函数调用new f时,this为一个新构造的对象,其原型为f.prototype;
最后是以callapply方式调用,this为传入的参数


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

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

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

【热门文章】
【热门文章】