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来创建实例 调用,都可以实现内化的类式创建,避免了调用错误。