月燕如 2015-05-01 13:32 采纳率: 33.3%
浏览 1773
已采纳

underscore.js的bind函数

先贴代码:
var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {
if (!(callingContext instanceof boundFunc))
return sourceFunc.apply(context, args);
var self = baseCreate(sourceFunc.prototype);
var result = sourceFunc.apply(self, args);
if (_.isObject(result))
return result;
return self;
};

// Create a function bound to a given object (assigning this, and arguments,
// optionally). Delegates to ECMAScript 5's native Function.bind if
// available.
.bind = function(func, context) {
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');
var args = slice.call(arguments, 2);
var bound = function() {
return executeBound(func, bound, context, this, args.concat(slice.call(arguments)));
};
return bound;
};
想问下,executeBound(func, bound, context, this, args.concat(slice.call(arguments)))这个里面的this是否就是指代调用_.bound的对象,然后后面为何要做(!(callingContext instanceof boundFunc))这个判断,网上查了好久,没查出来,请高手指导下,非常感谢

  • 写回答

1条回答 默认 最新

  • Go 旅城通票 2015-05-02 02:41
    关注

    这个得看如何调用的,因为this对象可以通过call和apply进行更改,如果不是通过apply或者call执行调用的,那么就是指向bound的实例对象了

    instanceof是判断对象是否属于某一类型。如果你不判断,可能会出错。因为要调用这个类型的方法,不是这个类型的实例可能方法不存在而出错

    http://www.ibm.com/developerworks/cn/web/1306_jiangjj_jsinstanceof/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化