Skip to content

Instantly share code, notes, and snippets.

@coolicer
Created July 24, 2013 02:15
Show Gist options
  • Save coolicer/6067631 to your computer and use it in GitHub Desktop.
Save coolicer/6067631 to your computer and use it in GitHub Desktop.
_.bind
//_.bind方法是把func绑定到obj上
var ctor = function(){};
_.bind = function(func, context) {
var args, bound;
//如果有原生则使用原生的bind方法
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() {
//如果没有实例化,就进入这个分支,使用apply模拟bind
if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
/*
如果已经被实例化,进入下面的代码。
ctor继承func,self为实例副本。
*/
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;
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment