underscore源码解析1

简介: _.noop()不论传递给它的是什么参数,返回的都是undefined。_.noop()=> undefined//函数如果没有return返回值的话,默认的就是返回undefined。
  1. _.noop()
    不论传递给它的是什么参数,返回的都是undefined。

_.noop()
=> undefined

//函数如果没有return返回值的话,默认的就是返回undefined。
_.noop = function() {};
  1. _.random(min,max)
    返回一个min和max之间的随机整数。如果你只传递了一个参数,那么将返回0和这个参数之间的整数。

_.random(0,100);
=> 42

_.random = function(min,max) {
//如果只传了一个参数的话,就把max的值设置为这个参数,而min设为0
  if (max == null) {
    max = min;
    min = 0;
  }
  return min + Math.floor(Math.random() * (max - min + 1));
};

Math.random()方法返回大于0小于1的一个随机数。
Math.floor()方法执行向下舍入,即它总是将数值向下舍入为最接近的整数。

  1. _.now()
    一个优化的方式来获取一个当前时间的整数时间戳。可用于实现定时/动画功能。

_.now();
=> 1503801043810

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

Date.now是ES5提出来的方法,如果浏览器支持,就等于这个方法,表示调用这个方法时的日期和时间的毫秒数。
反之就使用new操作符和Date构造函数创建一个日期对象,在调用Date构造函数而不传递参数的情况下,新创建的对象自动获得当前的日期和时间,再调用getTime方法,返回表示日期的毫秒数。

  1. _.uniqueId([prefix])
    为需要的客户端模型或DOM元素生成一个全局唯一的id。如果prefix参数存在,id将附加给它。

.uniqueId('contact');
=> 'contact_1'

var idCounter = 0;
_.uniqueId = function(prefix) {
  var id = ++idCounter + '';
  return prefix ? prefix + id : id;
}
  1. noConflict
    放弃Underscore的控制变量“_”。返回Underscore对象的引用。

var underscore = _.noConflict();

//‘this’是指向_的,准确的说是内部的_
var root = this;
var previousUnderscore = root._;

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

拿上面的例子来说,就是把这个控制变量"_"返回给了underscore;就像是jquery的“$”符号noConflict以后调用就要用jQuery('div')一样的效果,避免全局变量冲突。

  1. _.identity(value)
    返回与传入参数相等的值。相当于数学里的:f(x) = x
    这个函数看似无用,但是在Underscore里被用作默认的迭代器iterator

var stooge = {name : 'moe'};
=> stooge === ._identity(stooge)
=> true

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

就是把传入的参数返回

  1. .constant(value)
    创建一个函数,这个函数返回相同的值用来作为
    .constant的参数。

var stooge = {name: 'moe'};
stooge === _.constant(stooge)();
=> true

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

返回一个函数,这个函数再返回这个传入的参数。(返回一个能返回参数本身的函数)

  1. _.isUndefined(value)
    如果value是undefined,返回true。

_.isUndefined(window.missingVariable);
=> true

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

学习参考http://www.qdfuns.com/house/17398/note/class/id/bb6dc3cabae6651b94f69bbd562ff370/page/2.html
https://github.com/hanzichi/underscore-analysis/blob/master/underscore-1.8.3.js/underscore-1.8.3-analysis.js
http://www.css88.com/doc/underscore/#isEmpty
http://www.css88.com/doc/underscore/docs/underscore.html

目录
相关文章

推荐镜像

更多