开发者社区> 问答> 正文

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))这个判断,网上查了好久,没查出来,请高手指导下,非常感谢

展开
收起
小旋风柴进 2016-03-17 13:44:02 2246 0
1 条回答
写回答
取消 提交回答
  • 这个得看如何调用的,因为this对象可以通过call和apply进行更改,如果不是通过apply或者call执行调用的,那么就是指向bound的实例对象了

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

    2019-07-17 19:05:14
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
JavaScript函数 立即下载
Delivering Javascript to World 立即下载
编程语言如何演化-以JS的private为例 立即下载