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

underscore 复习 对象函数 篇章

时间:2015-03-13 18:14:13      阅读:2629      评论:0      收藏:1      [点我收藏+]

标签:

_.partial = function(func) {
    var boundArgs = slice.call(arguments, 1);
    var bound = function() {
      var position = 0, length = boundArgs.length;
      var args = Array(length);
      for (var i = 0; i < length; i++) {
        args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];
      }
      while (position < arguments.length) args.push(arguments[position++]);
      return executeBound(func, bound, this, this, args);
    };
    return bound;
  };

 

var baseCreate = function(prototype) { if (!_.isObject(prototype)) return {}; if (nativeCreate) return nativeCreate(prototype); Ctor.prototype = prototype; var result = new Ctor; Ctor.prototype = null; return result; };
var Ctor = function(){};

 bind,partial 方法的基础方法, 继承一个对象的所有属性

这里传入对象的英文诗 prototype ,这里的作用就是复制一个对象构造函数的原型属性

Ctor.prototype = prototype; 实现继承
var result = new Ctor; 创建实例
Ctor.prototype = null;清空通用helper函数的 原型
最后返回这个对象

bind函数,比较有用的一个锁定作用域的函数
 _.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;
  };

 优先检查是否存在 ecmascript5 的方法, 如果存在,则直接调用 原生方法

如果传入的 第一个参数不是 函数,那么直接抛出异常信息

局部变量 args 是 保存,除了需要 绑定的 func 名字 和 上下文 context信息之外的 其他 参数的信息数组,便于以后直接进行调用 concat

构造绑定函数 bound

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;
  };

 这里的 callingContext 是 你绑定的那个函数 所在的作用域

如果 callingContext 是 boundFunc的实例 (这种情况感觉非常之少,作者考虑得很全面和周到,实在是汗颜)那么会执行下面的语句

由于 callContext已经是实例了,那么 self的作用域已经默认绑定到了 需要 额外绑定的 obj上,所以 之后的 self 与 之前的 context 是同一个 作用域

_.partial = function(func) {
    var boundArgs = slice.call(arguments, 1);
    var bound = function() {
      var position = 0, length = boundArgs.length;
      var args = Array(length);
      for (var i = 0; i < length; i++) {
        args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];
      }
      while (position < arguments.length) args.push(arguments[position++]);
      return executeBound(func, bound, this, this, args);
    };
    return bound;
  };

 函数式编程又一个很好用的函数 partial ,锁住某些参数,以备之后调用

boundArgs 切割出 除了func 之外的所有参数

当调用 bound方法的时候 boundArgs在前, 本身调用的 参数 arguments 数组在后, 这里作者提供了一个插值的设定,如果 boundargs本身是 underscore ,那么就用arguments还未使用的 参数去代替这个_

bindAll

_.bindAll = function(obj) {
    var i, length = arguments.length, key;
    if (length <= 1) throw new Error(‘bindAll must be passed function names‘);
    for (i = 1; i < length; i++) {
      key = arguments[i];
      obj[key] = _.bind(obj[key], obj);
    }
    return obj;
  };

 传入 一个对象 ,一些方法 func reference name

遍历 func name 然后 加 name作为key值 ,绑定作用域的函数作为  value值进行绑定,最终返回这个obj

Delay

_.delay = function(func, wait) {
    var args = slice.call(arguments, 2);
    return setTimeout(function(){
      return func.apply(null, args);
    }, wait);
  };

 没啥好说的,延时执行函数,可以额外添加参数

defer

_.defer = _.partial(_.delay, _, 1);

defer 就用到了占位符 _,这样可以 让 func

 throttle

 _.throttle = function(func, wait, options) {
    var context, args, result;
    var timeout = null;
    var previous = 0;
    if (!options) options = {};
    var later = function() {
      previous = options.leading === false ? 0 : _.now();
      timeout = null;
      result = func.apply(context, args);
      if (!timeout) context = args = null;
    };
    return function() {
      var now = _.now();
      if (!previous && options.leading === false) previous = now;
      var remaining = wait - (now - previous);
      context = this;
      args = arguments;
      if (remaining <= 0 || remaining > wait) {
        if (timeout) {
          clearTimeout(timeout);
          timeout = null;
        }
        previous = now;
        result = func.apply(context, args);
        if (!timeout) context = args = null;
      } else if (!timeout && options.trailing !== false) {
        timeout = setTimeout(later, remaining);
      }
      return result;
    };
  };

 throttle 确保 回调函数 func 只在 wait的时间 内执行一次,假设wait是1000ms

 如果 在 wait 时间之内 调用, 那么会 等到 wait的时间进行执行

即 点击2次,执行2次, 但是是 1秒执行一次,不会再1s之内执行2次

这里有2个可用的 option

leading 是 false的情况, 表示 必须等待 wait 之后才执行第一次

trailing 是 false的情况,就是wait时间之内点击 2次的,第二次是永远不会触发的

即为 timeout = setTimeout(later, remaining); 这句话是不执行的throttle 常用的点是 在 window 监听scroll的时候,会加快性能,不会闪烁

debounce

_.debounce = function(func, wait, immediate) {
    var timeout, args, context, timestamp, result;

    var later = function() {
      var last = _.now() - timestamp;

      if (last < wait && last >= 0) {
        timeout = setTimeout(later, wait - last);
      } else {
        timeout = null;
        if (!immediate) {
          result = func.apply(context, args);
          if (!timeout) context = args = null;
        }
      }
    };

    return function() {
      context = this;
      args = arguments;
      timestamp = _.now();
      var callNow = immediate && !timeout;
      if (!timeout) timeout = setTimeout(later, wait);
      if (callNow) {
        result = func.apply(context, args);
        context = args = null;
      }

      return result;
    };
  };

 debounce

如果在 wait的time内频繁触发事件的话,只有最后一次超过wait的事件才会执行,如果传入immediate 为true的话,那么会立即执行第一次的调用

 wrap 预装方法,有点测试方法的感觉

_.wrap = function(func, wrapper) {
    return _.partial(wrapper, func);
  };

 这里用到 partial 函数 partial函数 里面 wrapper是执行的函数,而func是一个参数,将func 传入 wrapper ,执行func

example:

var hello = function(name) { return "hello: " + name; };
hello = _.wrap(hello, function(func) {
  return "before, " + func("moe") + ", after";
});
hello();
=> ‘before, hello: moe, after‘

 negate :将 predicate的 Boolean值反转

 _.negate = function(predicate) {
    return function() {
      return !predicate.apply(this, arguments);
    };
  };

 compose

_.compose = function() {
    var args = arguments;
    var start = args.length - 1;
    return function() {
      var i = start;
      var result = args[start].apply(this, arguments);
      while (i--) result = args[i].call(this, result);
      return result;
    };
  };

 将一组函数传入compse,倒序执行,然后将每一个函数的结果 作为参数 给到下一个函数

after:

_.after = function(times, func) {
    return function() {
      if (--times < 1) {
        return func.apply(this, arguments);
      }
    };
  };

 在函数执行 times -1  次之后,再执行 func

before:

_.before = function(times, func) {
    var memo;
    return function() {
      if (--times > 0) {
        memo = func.apply(this, arguments);
      }
      if (times <= 1) func = null;
      return memo;
    };
  };

 函数只能 执行 times -1  次

once 用到了 partial的padding

 _.once = _.partial(_.before, 2);

 这里传入 before ,然后 before调用的时候 args是 2是第一个参数,传入的func是第二个参数,这样就用到 before的接口,由于 2是一个常量,所以func函数只执行一次

接下来是 object functions

var hasEnumBug = !{toString: null}.propertyIsEnumerable(‘toString‘);

ie9- : toString 是不能被 for key in object 进行遍历的

这里的 hasEnumBug 是一个 Boolean 的 标识符
var nonEnumerableProps = [‘valueOf‘, ‘isPrototypeOf‘, ‘toString‘,
                      ‘propertyIsEnumerable‘, ‘hasOwnProperty‘, ‘toLocaleString‘];
不能被遍历的 属性列表
function collectNonEnumProps(obj, keys) {
    var nonEnumIdx = nonEnumerableProps.length;
    var constructor = obj.constructor;
    var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto;
    var prop = ‘constructor‘;
    if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);

    while (nonEnumIdx--) {
      prop = nonEnumerableProps[nonEnumIdx];
      if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
        keys.push(prop);
      }
    }
  }

 这个方法属于破坏性的方法, keys本身传递进去是一个引用,这里遍历了所有 不能被 遍历属性,如果 对象有这个属性值,那么keys就会推入这个属性,而特殊属性属性 constructor 也会进行单独的判断

keys :

_.keys = function(obj) {
    if (!_.isObject(obj)) return [];
    if (nativeKeys) return nativeKeys(obj);
    var keys = [];
    for (var key in obj) if (_.has(obj, key)) keys.push(key);
    if (hasEnumBug) collectNonEnumProps(obj, keys);
    return keys;
  };

 返回对象所有的属性值,如果是ie9-,那么调用 collectNonEnumProps 推入这些属性(这里又调用_.has,将不包括prototype的属性)

allKeys

_.allKeys = function(obj) {
    if (!_.isObject(obj)) return [];
    var keys = [];
    for (var key in obj) keys.push(key);
    if (hasEnumBug) collectNonEnumProps(obj, keys);
    return keys;
  };

 返回所有的keys值,包括 prototype属性

values:

 _.values = function(obj) {
    var keys = _.keys(obj);
    var length = keys.length;
    var values = Array(length);
    for (var i = 0; i < length; i++) {
      values[i] = obj[keys[i]];
    }
    return values;
  };

 返回根据keys 函数得到的 values的数组

mapObject

_.mapObject = function(obj, iteratee, context) {
    iteratee = cb(iteratee, context);
    var keys =  _.keys(obj),
          length = keys.length,
          results = {},
          currentKey;
      for (var index = 0; index < length; index++) {
        currentKey = keys[index];
        results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
      }
      return results;
  };

 对象 map遍历的实现,于数组遍历的实现相同 cb 函数 参见 第一篇关于 underscore的博客

pairs

 _.pairs = function(obj) {
    var keys = _.keys(obj);
    var length = keys.length;
    var pairs = Array(length);
    for (var i = 0; i < length; i++) {
      pairs[i] = [keys[i], obj[keys[i]]];
    }
    return pairs;
  };

 将 key,value作为一个数组0,1的索引进行展现

invert

_.invert = function(obj) {
    var result = {};
    var keys = _.keys(obj);
    for (var i = 0, length = keys.length; i < length; i++) {
      result[obj[keys[i]]] = keys[i];
    }
    return result;
  };

 将数组 key和value的位置互换,这里需要注意的是 value值 必须是合法的key值,不然会报错,并不是非常实用的方法

function

_.functions = _.methods = function(obj) {
    var names = [];
    for (var key in obj) {
      if (_.isFunction(obj[key])) names.push(key);
    }
    return names.sort();
  };

 返回一个对象 经过 默认 sort排序的函数列表

var createAssigner = function(keysFunc, undefinedOnly) {
    return function(obj) {
      var length = arguments.length;
      if (length < 2 || obj == null) return obj;
      for (var index = 1; index < length; index++) {
        var source = arguments[index],
            keys = keysFunc(source),
            l = keys.length;
        for (var i = 0; i < l; i++) {
          var key = keys[i];
          if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];
        }
      }
      return obj;
    };
  };
_.extend = createAssigner(_.allKeys)
_.extendOwn = _.assign = createAssigner(_.keys);

 underscore extends 的 实现

巧妙实用参数个数实现,与其他库的extends的实现有一点不同,支持传入 undefinedOnly,如果 dest obj 的key值为 undefined的话,再进行覆盖值的操作,这里采用了functional 函数式编程的思想allKeys就是 带 原型属性, key只是带实例的属性

findKey

 _.findKey = function(obj, predicate, context) {
    predicate = cb(predicate, context);
    var keys = _.keys(obj), key;
    for (var i = 0, length = keys.length; i < length; i++) {
      key = keys[i];
      if (predicate(obj[key], key, obj)) return key;
    }
  };

 obj find的实现,找到第一个符合 predicate函数的 值,并返回,这里与find不同的是,返回的是对象

pick

_.pick = function(object, oiteratee, context) {
    var result = {}, obj = object, iteratee, keys;
    if (obj == null) return result;
    if (_.isFunction(oiteratee)) {
      keys = _.allKeys(obj);
      iteratee = optimizeCb(oiteratee, context);
    } else {
      keys = flatten(arguments, false, false, 1);
      iteratee = function(value, key, obj) { return key in obj; };
      obj = Object(obj);
    }
    for (var i = 0, length = keys.length; i < length; i++) {
      var key = keys[i];
      var value = obj[key];
      if (iteratee(value, key, obj)) result[key] = value;
    }
    return result;
  };

 这里留了一个 插件的机制,就是可以传入自定义的 iterate 函数,默认是 获取 obj里面是否存在key,而如果oiteratee 本身是函数的,可以使用这个作为逻辑判断

flatten 第二个和第三个参数 是true,表示深层 扁平化数组,最后index是1,就是过滤第一个arguments的 obj

omit

_.omit = function(obj, iteratee, context) {
    if (_.isFunction(iteratee)) {
      iteratee = _.negate(iteratee);
    } else {
      var keys = _.map(flatten(arguments, false, false, 1), String);
      iteratee = function(value, key) {
        return !_.contains(keys, key);
      };
    }
    return _.pick(obj, iteratee, context);
  };

 如果传入的 iteratee是function,那么使用这个函数作为omit的逻辑。不是的话,默认使用 contains作为 判断

最后修正 iterate 之后 调用pick方法计算结果

defaults

_.defaults = createAssigner(_.allKeys, true);

 返回所有 不是undefined的值 对象属性 作为  default 默认值

clone:潜度复制

_.clone = function(obj) {
    if (!_.isObject(obj)) return obj;
    return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
  };

 如果不是对象,直接返回,如果是数组,使用slice切片,如果是对象,调用extend方法,由于extend方法内部是没有递归的,所以是shadow copy

tap

_.tap = function(obj, interceptor) {
    interceptor(obj);
    return obj;
  };

 拦截器,多用于测试代码

isMatch

_.isMatch = function(object, attrs) {
    var keys = _.keys(attrs), length = keys.length;
    if (object == null) return !length;
    var obj = Object(object);
    for (var i = 0; i < length; i++) {
      var key = keys[i];
      if (attrs[key] !== obj[key] || !(key in obj)) return false;
    }
    return true;
  };

 如果 对象的属性 包含  attrs 的属性,那么就是返回true ,这里的基准是根据 attrs的属性个数来决定的,不包含prototype的属性,这里用的是 全等匹配,如果是对象的话,必须引用一致

internal function:eq

  var eq = function(a, b, aStack, bStack) {
    if (a === b) return a !== 0 || 1 / a === 1 / b;
    if (a == null || b == null) return a === b;
    if (a instanceof _) a = a._wrapped;
    if (b instanceof _) b = b._wrapped;
    Compare [[Class]] names.
    var className = toString.call(a);
    if (className !== toString.call(b)) return false;
    switch (className) {
      case ‘[object RegExp]‘:
      case ‘[object String]‘:
        return ‘‘ + a === ‘‘ + b;
      case ‘[object Number]‘:
        if (+a !== +a) return +b !== +b;
        return +a === 0 ? 1 / +a === 1 / b : +a === +b;
      case ‘[object Date]‘:
      case ‘[object Boolean]‘:
        return +a === +b;
    }
    var areArrays = className === ‘[object Array]‘;
    if (!areArrays) {
      if (typeof a != ‘object‘ || typeof b != ‘object‘) return false;
      var aCtor = a.constructor, bCtor = b.constructor;
      if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
                               _.isFunction(bCtor) && bCtor instanceof bCtor)
                          && (‘constructor‘ in a && ‘constructor‘ in b)) {
        return false;
      }
    }
    aStack = aStack || [];
    bStack = bStack || [];
    var length = aStack.length;
    while (length--) {
      if (aStack[length] === a) return bStack[length] === b;
    }
    aStack.push(a);
    bStack.push(b);
    if (areArrays) {
      length = a.length;
      if (length !== b.length) return false;
      while (length--) {
        if (!eq(a[length], b[length], aStack, bStack)) return false;
      }
    } else {
      var keys = _.keys(a), key;
      length = keys.length;
      if (_.keys(b).length !== length) return false;
      while (length--) {
        key = keys[length];
        if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
      }
    }
    aStack.pop();
    bStack.pop();
    return true;
  };

 代码有点长,慢慢分析

if (a === b) return a !== 0 || 1 / a === 1 / b;

Identical objects are equal. 0 === -0, but they aren’t identical.

这里作者的判断非常的严格,足见其涉猎 很深,一般 全等后,应该直接返回boolean,但是作者还进行了一次判断,是我们需要不断拓展学习的

if (a == null || b == null) return a === b;

如果 a 和 b 有 null 值的话, 直接返回他们的全等结果
 if (a instanceof _) a = a._wrapped;
 if (b instanceof _) b = b._wrapped;
这里 其实 是一个 实例方法
underscore内部提供了一个实例化的方法
 var _ = function(obj) {
    if (obj instanceof _) return obj;
    if (!(this instanceof _)) return new _(obj);
    this._wrapped = obj;
  };

 可以实例化一个新的underscore的对象,这个对象本身可以包含一个 wrapped属性,这个属性就是传入 constructor 的参数

var className = toString.call(a);
if (className !== toString.call(b)) return false;
这里是一个很经典的 toString object的方法,用来判断 对象的类型,如果2个对象的类型都不一致的话,那么就没有进行比较的必要了
下面是各种 switch case的情况
regexp,string, ‘‘ + a === ‘‘ + b; 将a和b String 化, 这个在 jquery 的 className里面也有涉及 ,空字符串 + 变量,强制转换为 string的类型
number : if (+a !== +a) return +b !== +b; 这里有判断 NAN 的情况,2个NAN是默认不相等的
然后对0进行判断,然后对其他数字进行判断 +a === 0 ? 1 / +a === 1 / b : +a === +b;
date boolean: 直接返回 全等的结果
var areArrays = className === ‘[object Array]‘;
如果不是 array,那么进入 object的判断
如果 a 和 b 有一个 不是object , 那么直接返回false
 var aCtor = a.constructor, bCtor = b.constructor;
      if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
                               _.isFunction(bCtor) && bCtor instanceof bCtor)
                          && (‘constructor‘ in a && ‘constructor‘ in b)) {
        return false;
      }
    }

 这里对于对象的判断的概念有点模糊,希望高手赐教

英文的解释是:Objects with different constructors are not equivalent, butObjects or Arrays from different frames are.

如果此时还没有 return,2种情况,一种是 array 一种是 object

如果传入了 aStack 和 bStack的值(递归的情况)

那么获取stack的值,后序遍历,如果在 astack中找到 a值的话,去判断bstack 相应的索引位置是否是 b值

如果此时还没有return,那么将a和b的值分别推入 astack 和 bstack中去

if (areArrays) {
      length = a.length;
      if (length !== b.length) return false;
      while (length--) {
        if (!eq(a[length], b[length], aStack, bStack)) return false;
      }
    } else {
      var keys = _.keys(a), key;
      length = keys.length;
      if (_.keys(b).length !== length) return false;
      while (length--) {
        key = keys[length];
        if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
      }
    }

 如果做了优化,如果2个数组的长度都不相等的话,直接返回false

如果长度相等,那么进行递归 eq的操作

对象也是同理,获取key值,进行比较

aStack.pop();
bStack.pop();

比较完之后 将比较的值推出数组

equal
_.isEqual = function(a, b) {
    return eq(a, b);
  };

 深度比较a和b的值,返回boolean

isEmpty

 _.isEmpty = function(obj) {
    if (obj == null) return true;
    if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;
    return _.keys(obj).length === 0;
  };

 如果 对象是 null 直接返回 true

如果 对象是类数组的,并且 对象是数组或者字符串或者 arguments参数,那么返回 对象的长度是否是0

否则认为 是一个 纯对象,获取 非原型属性判断 keys 的 length 是否是0

isElement

_.isElement = function(obj) {
    return !!(obj && obj.nodeType === 1);
  };

 判断是否为对象,并且 nodeType 的 类型是 1

isArray

 _.isArray = nativeIsArray || function(obj) {
    return toString.call(obj) === ‘[object Array]‘;
  };

 判断是否存在 native 方法, 没有的话用 fallback 

isObject

_.isObject = function(obj) {
    var type = typeof obj;
    return type === ‘function‘ || type === ‘object‘ && !!obj;
  };

 判断对象是 函数 或者是 非空的对象

_.each([‘Arguments‘, ‘Function‘, ‘String‘, ‘Number‘, ‘Date‘, ‘RegExp‘, ‘Error‘], function(name) {
    _[‘is‘ + name] = function(obj) {
      return toString.call(obj) === ‘[object ‘ + name + ‘]‘;
    };
  });

 ioc的方式 实现 定义函数, 这个 ioc 是网上 说的, 具体由于不是很懂ioc的知识,这里知识借鉴一下 ,jquery也有相应的实现

ie9- 对于  isArguments 的实现

if (!_.isArguments(arguments)) {
    _.isArguments = function(obj) {
      return _.has(obj, ‘callee‘);
    };
  }

 isFunction  对于 某些版本浏览器的修正

if (typeof /./ != ‘function‘ && typeof Int8Array != ‘object‘) {
    _.isFunction = function(obj) {
      return typeof obj == ‘function‘ || false;
    };
  }

 isFinite

_.isFinite = function(obj) {
    return isFinite(obj) && !isNaN(parseFloat(obj));
  };

 判断 obj 是 有限的,并且 数字化 obj 不是NAN

isBoolean

_.isBoolean = function(obj) {
    return obj === true || obj === false || toString.call(obj) === ‘[object Boolean]‘;
  };

 判断对象是不是 true,false,或者 toString之后是 object Boolean

isNull

_.isNull = function(obj) {
    return obj === null;
  };

 直接全等判断是否是null

isUndefined

_.isUndefined = function(obj) {
    return obj === void 0;
  };

 判断obj是否全等于 undefined (void 0是最新的写法)

has

_.has = function(obj, key) {
    return obj != null && hasOwnProperty.call(obj, key);
  };

 判断obj是否是null,并且obj 非prototype属性是否包含key值

UTILITY FUNCTIONS

noConflict

 _.noConflict = function() {
    root._ = previousUnderscore;
    return this;
  };

 把_给到之前一个使用 下划线标识符 _的对象上

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

 3组函数,函数式编程特有方法,有时候没有func,要想传值,直接传递function,保持调用接口一致

propertyOf

_.propertyOf = function(obj) {
    return obj == null ? function(){} : function(key) {
      return obj[key];
    };
  };

 如果obj是null,返回空函数,返回空函数也是为了传递function的时候,保持api接口一致

这里是锁住obj,然后可以调用的时候 提取obj的key值

matcher

_.matcher = _.matches = function(attrs) {
    attrs = _.extendOwn({}, attrs);
    return function(obj) {
      return _.isMatch(obj, attrs);
    };
  };

 返回一个 predicate函数,匹配 attrs的 自有属性 是否与给到obj属性的值一致,返回的是boolean

times

_.times = function(n, iteratee, context) {
    var accum = Array(Math.max(0, n));
    iteratee = optimizeCb(iteratee, context, 1);
    for (var i = 0; i < n; i++) accum[i] = iteratee(i);
    return accum;
  };

 执行一个函数 n 次

random

_.random = function(min, max) {
    if (max == null) {
      max = min;
      min = 0;
    }
    return min + Math.floor(Math.random() * (max - min + 1));
  };

 如果第二个参数不存在, min为0 , max为 第一个参数

得到 min- max 的一个随机整数

now:

_.now = Date.now || function() {
    return new Date().getTime();
  };

 获取当前的 时间戳

var escapeMap = {
    ‘&‘: ‘&‘,
    ‘<‘: ‘<‘,
    ‘>‘: ‘>‘,
    ‘"‘: ‘"‘,
    "‘": ‘‘‘,
    ‘`‘: ‘`‘
  };
  var unescapeMap = _.invert(escapeMap);

 定义 encode map 和 decode map

var createEscaper = function(map) {
    var escaper = function(match) {
      return map[match];
    };
    var source = ‘(?:‘ + _.keys(map).join(‘|‘) + ‘)‘;
    var testRegexp = RegExp(source);
    var replaceRegexp = RegExp(source, ‘g‘);
    return function(string) {
      string = string == null ? ‘‘ : ‘‘ + string;
      return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
    };
  };
var source = ‘(?:‘ + _.keys(map).join(‘|‘) + ‘)‘;

 动态正则 ,叼的飞起。一般人是不是就手动 输入了

var testRegexp = RegExp(source);
var replaceRegexp = RegExp(source, ‘g‘);

 定义2个正则,一个 test 用,一个用于替换

_.escape = createEscaper(escapeMap);
 _.unescape = createEscaper(unescapeMap);

 使用闭包创建2个 函数, escape和 unescape

result:

_.result = function(object, property, fallback) {
    var value = object == null ? void 0 : object[property];
    if (value === void 0) {
      value = fallback;
    }
    return _.isFunction(value) ? value.call(object) : value;
  };

 如果 object是 null, value给予第三个参数

如果 value是函数,在obejct的context下立即执行这个函数,如果不是就返回value的值

var idCounter = 0;
  _.uniqueId = function(prefix) {
    var id = ++idCounter + ‘‘;
    return prefix ? prefix + id : id;
 };

 返回一个 自增的 unique id ,支持传入 prefix

接下来是 underscore 内置的 重头戏  template 方法

_.templateSettings = {
    evaluate    : /<%([\s\S]+?)%>/g,
    interpolate : /<%=([\s\S]+?)%>/g,
    escape      : /<%-([\s\S]+?)%>/g
 };

templateSettings regex map

evaluate : 需要执行的块

interpolate: 插值块,直接放变量

escape : 转义块

var noMatch = /(.)^/;

 如果要自定义 templateSetting ,那么必须有一个正则确保 不会被匹配到

var escapes = {
    "‘":      "‘",
    ‘\\‘:     ‘\\‘,
    ‘\r‘:     ‘r‘,
    ‘\n‘:     ‘n‘,
    ‘\u2028‘: ‘u2028‘,
    ‘\u2029‘: ‘u2029‘
  };

 某些特殊字符需要转义的部分

var escaper = /\\|‘|\r|\n|\u2028|\u2029/g;
 var escapeChar = function(match) {
    return ‘\\‘ + escapes[match];
  };

 特殊字符的转义函数(构造成为 new Regex 需要字符串的形式,双重转义)

_.template = function(text, settings, oldSettings) {
    if (!settings && oldSettings) settings = oldSettings;
    settings = _.defaults({}, settings, _.templateSettings);
    var matcher = RegExp([
      (settings.escape || noMatch).source,
      (settings.interpolate || noMatch).source,
      (settings.evaluate || noMatch).source
    ].join(‘|‘) + ‘|$‘, ‘g‘);
    var index = 0;
    var source = "__p+=‘";
    text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
      source += text.slice(index, offset).replace(escaper, escapeChar);
      index = offset + match.length;
      if (escape) {
        source += "‘+\n((__t=(" + escape + "))==null?‘‘:_.escape(__t))+\n‘";
      } else if (interpolate) {
        source += "‘+\n((__t=(" + interpolate + "))==null?‘‘:__t)+\n‘";
      } else if (evaluate) {
        source += "‘;\n" + evaluate + "\n__p+=‘";
      }
      return match;
    });
    source += "‘;\n";
    if (!settings.variable) source = ‘with(obj||{}){\n‘ + source + ‘}\n‘;
    try {
      var render = new Function(settings.variable || ‘obj‘, ‘_‘, source);
    } catch (e) {
      e.source = source;
      throw e;
    }
    var template = function(data) {
      return render.call(this, data, _);
    };
    var argument = settings.variable || ‘obj‘;
    template.source = ‘function(‘ + argument + ‘){\n‘ + source + ‘}‘;

    return template;
  };

 template的setting 可以自定义

var matcher = RegExp([
      (settings.escape || noMatch).source,
      (settings.interpolate || noMatch).source,
      (settings.evaluate || noMatch).source
 ].join(‘|‘) + ‘|$‘, ‘g‘);

 发现很多库把 join 用得 很顺手,还比如字符串的拼接,确实看起来挺美的

template的原理是动态创建一个 函数, 函数的 方法体是 source ,source是根据模板 转换后 拼接出来的

text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
      source += text.slice(index, offset).replace(escaper, escapeChar);
      index = offset + match.length;
      if (escape) {
        source += "‘+\n((__t=(" + escape + "))==null?‘‘:_.escape(__t))+\n‘";
      } else if (interpolate) {
        source += "‘+\n((__t=(" + interpolate + "))==null?‘‘:__t)+\n‘";
      } else if (evaluate) {
        source += "‘;\n" + evaluate + "\n__p+=‘";
      }
      return match;
    });

 转义3个 map,对应 match 的3个分组, escape,interpolate,evaluate,__t 是一个字符串,最后生成的是一个模板变量

var render = new Function(settings.variable || ‘obj‘, ‘_‘, source);

 这里又复习了下基础知识,这里 最后一个参数是 方法体,前面2个参数都是 render之后调用的参数,这里 settings.variable是之前 自定义的 setting的值

最后返回了一个 template 函数

var template = function(data) {
     return render.call(this, data, _);
 };

 然后可以传递obj进去,进行模板的解析, template根据目前的学习来看,还是对于 模板边界的约定,以及正则的使用处理,以后接触 jade  和 handlebars 的时候可以再学习下

chain

_.chain = function(obj) {
    var instance = _(obj);
    instance._chain = true;
    return instance;
  };

 这里把 obj 封装为 一个 可以使用 underscore  方法的对象,保存对于 obj对象的引用

官网的 example

var stooges = [{name: ‘curly‘, age: 25}, {name: ‘moe‘, age: 21}, {name: ‘larry‘, age: 23}];
var youngest = _.chain(stooges)
  .sortBy(function(stooge){ return stooge.age; })
  .map(function(stooge){ return stooge.name + ‘ is ‘ + stooge.age; })
  .first()
  .value();
=> "moe is 21"

内置的一些oop的方法,都是方便内部进行调用,集成

内部 result 方法

 var result = function(instance, obj) {
    return instance._chain ? _(obj).chain() : obj;
  };

 mixin:

_.mixin = function(obj) {
    _.each(_.functions(obj), function(name) {
      var func = _[name] = obj[name];
      _.prototype[name] = function() {
        var args = [this._wrapped];
        push.apply(args, arguments);
        return result(this, func.apply(_, args));
      };
    });
  };

 将 obj 的属性 混合给到 underscore 中去,如果 underscore是一个封装对象的话, this._wrapped是一个 封装对象的实例,这里有点饶,一会再看几遍

_.each([‘pop‘, ‘push‘, ‘reverse‘, ‘shift‘, ‘sort‘, ‘splice‘, ‘unshift‘], function(name) {
    var method = ArrayProto[name];
    _.prototype[name] = function() {
      var obj = this._wrapped;
      method.apply(obj, arguments);
      if ((name === ‘shift‘ || name === ‘splice‘) && obj.length === 0) delete obj[0];
      return result(this, obj);
    };
 });
 _.each([‘concat‘, ‘join‘, ‘slice‘], function(name) {
    var method = ArrayProto[name];
    _.prototype[name] = function() {
      return result(this, method.apply(this._wrapped, arguments));
    };
  });

将数组 的 默认方法  添加到  underscore的 原型方法中去,方便调用

_.prototype.value = function() {
    return this._wrapped;
};
_.prototype.valueOf = _.prototype.toJSON = _.prototype.value;
_.prototype.toString = function() {
   return ‘‘ + this._wrapped;
};

 underscore 原型value方法,返回 当前 underscore 实例的 wrapped的值

给予 value 方法 toJSON 和 valueOf的别名

最后覆盖 默认的 toString的方法

自此所有underscore的方法都已经复习完毕,以备之后自己复习之用

underscore 复习 对象函数 篇章

标签:

原文地址:http://www.cnblogs.com/horsefefe/p/4305806.html

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