underScore 源码解析(一)---- 结构

underScore适用于各种环境 

(function(){
    //code 从这里开始
   var root = this;
}).call(this);

这个估计已经算标准做法了,为什么这样可以避免命名空间污染

其中有两个知识点需要解释一下:

(function(){})   将函数声明包含在一对圆口号中,表示他实际上是一个函数表达式。---------《高级程序设计第3版》

 .call(this) 立即调用匿名函数,this在浏览器下 == window, 在其他环境中 == global 。

     call方法使用,可以参考https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/call

 var root = this;  Establishthe root object, window in the browser, or global on the server.

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 

 

  // Save the previous value of the `_` variable.
  var previousUnderscore = root._;

  // Establish the object that gets returned to break out of a loop iteration.
  var breaker = {};

  // 这样定义节省字节
  var ArrayProto = Array.prototype, 
     ObjProto = Object.prototype, 
    FuncProto = Function.prototype;

  // 预先定义,查找变量更快
  var slice            = ArrayProto.slice,
      concat           = ArrayProto.concat,
      unshift          = ArrayProto.unshift,
      toString         = ObjProto.toString,
      hasOwnProperty   = ObjProto.hasOwnProperty;

  // **ECMAScript 5** 原生方法,underScore不会重写原生方法
  var
    nativeForEach      = ArrayProto.forEach,
    nativeMap          = ArrayProto.map,
    nativeReduce       = ArrayProto.reduce,
    nativeReduceRight  = ArrayProto.reduceRight,
    nativeFilter       = ArrayProto.filter,
    nativeEvery        = ArrayProto.every,
    nativeSome         = ArrayProto.some,
    nativeIndexOf      = ArrayProto.indexOf,
    nativeLastIndexOf  = ArrayProto.lastIndexOf,
    nativeIsArray      = Array.isArray,
    nativeKeys         = Object.keys,
    nativeBind         = FuncProto.bind;

以上定义了一些变量。

 

// Create a safe reference to the Underscore object for use below.
  var _ = function(obj) {
    if (obj instanceof _) return obj;    //当obj是_的实例,返回
    if (!(this instanceof _)) return new _(obj);   //当作为函数调用时,通过判断(window || global)不是_的实例,创建一个对象,避免调用错误。
    this._wrapped = obj;
  };

该方法是创建一个作用域安全的构造函数,作为函数调用 或者 作为 new来创建实例 调用,都可以实现内化的类式创建,避免了调用错误。



 


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值