码迷,mamicode.com
首页 > 其他好文 > 详细

underscore源码解析

时间:2015-11-16 19:21:40      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:

underscore就是一些函数的集合,大概分为6部分,分别是基础函数,集合,数组,函数,对象,实用功能.

在实现每一个功能的时候,基本上先自己实现,再对比。

(function(){

}.call(this));
基本框架长这样,就一个函数的自调用,用window作为调用对象,防止污染全局。

//把window对象先存起来备用吧。
var root = this;
//弄个window的属性_;
var previousUnderscore = root._;
//存一些原型
var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
//存一些原型的方法
var
push = ArrayProto.push,
slice = ArrayProto.slice,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty;

var
nativeIsArray = Array.isArray,
nativeKeys = Object.keys,
nativeBind = FuncProto.bind,
nativeCreate = Object.create;
//弄个备用的构造函数
var Ctor = function(){};

//构造函数_,obj是_实例的话,直接返回obj.若是直接调用构造函数而不是通过new操作符的话,会调用第二个if.执行new _(obj).
//另外,这样的话obj就不是实例了,所以弄个实例属性_wrapped把obj存起来备用。
var _ = function(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
};
//这个是什么nodejs接口的,不懂。过了,嘿嘿
  if (typeof exports !== ‘undefined‘) {
    if (typeof module !== ‘undefined‘ && module.exports) {
      exports = module.exports = _;
    }
    exports._ = _;
  } else {
    root._ = _;
  }
//这个是关于函数优化的,参数函数,调用EC,参数数量。
//只传了一个参数的话,context==null.这里应该是可以用context === void 0或者context==null,一个意思。直接返回传入的函数
//没传第三个参数的话,默认就是传三个参数给调用的函数,一般是用在forEach,filter这些数组方法,function(element,index,array);
//第三个参数是1或2的话,感觉没什么特别的,直接调用吧.是4的话就是reduce函数之类的。
var optimizeCb = function(func, context, argCount) {
if (context === void 0) return func;
switch (argCount == null ? 3 : argCount) {
case 1: return function(value) {
return func.call(context, value);
};
case 2: return function(value, other) {
return func.call(context, value, other);
};
case 3: return function(value, index, collection) {
return func.call(context, value, index, collection);
};
case 4: return function(accumulator, value, index, collection) {
return func.call(context, accumulator, value, index, collection);
};
}
return function() {
return func.apply(context, arguments);
};
};


//没传参数的话,直接返回一个函数,设置a,调用这个函数a,返回传给a的参数
//value是函数的话,直接调用上面的函数优化公式,
//对象的话,返回
var cb = function(value, context, argCount) {
if (value == null) return _.identity;
if (_.isFunction(value)) return optimizeCb(value, context, argCount);
if (_.isObject(value)) return _.matcher(value);
return _.property(value);
};

_.identity = function(value) {
return value;
};
 

underscore源码解析

标签:

原文地址:http://www.cnblogs.com/wz0107/p/4969528.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!