// Object Functions
// ---------------- // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
/*
ie9以下版本中,对象中的key是不能被遍历的
*/
var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];// 不能被遍历的属性 var collectNonEnumProps = function(obj, keys) {
var nonEnumIdx = nonEnumerableProps.length;
var constructor = obj.constructor;
var proto = _.isFunction(constructor) && constructor.prototype || ObjProto;// 这是访问实例原型的一种方法!!!!!!!! // Constructor is a special case.
// Constructor是特殊的属性,单独处理一下
var prop = 'constructor';
// _.has()只访问自身属性,不行沿作用域链查找;_.contains()是用for in 查找,所以找不到不可遍历的属性
// 'constructor'在自身,但是for in 遍历不到
if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop); while (nonEnumIdx--) {
prop = nonEnumerableProps[nonEnumIdx];
// prop在obj上(也有可能在原型上),并且obj[prop]与原型上的值不一样,并且用for in找不到prop
if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
keys.push(prop);
}
}
}; // Retrieve the names of an object's own properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`.
/*
获取对象中的所有属性
*/
_.keys = function(obj) {
if (!_.isObject(obj)) return [];
if (nativeKeys) return nativeKeys(obj);// Object.keys(obj)
var keys = [];
for (var key in obj) if (_.has(obj, key)) keys.push(key);// _.has()会判断对象属性是否在本身对象里
// Ahem, IE < 9.
if (hasEnumBug) collectNonEnumProps(obj, keys);// 将不可遍历的属性也加进去
return keys;
}; // Retrieve all the property names of an object.
/*
检索object拥有的和继承的所有属性的名称
*/
_.allKeys = function(obj) {
if (!_.isObject(obj)) return [];
var keys = [];
for (var key in obj) keys.push(key);
// Ahem, IE < 9.
if (hasEnumBug) collectNonEnumProps(obj, keys);
return keys;
}; // Retrieve the values of an object's properties.
/*
通过_.keys()获取所有value
*/
_.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;
}; // Returns the results of applying the iteratee to each element of the object.
// In contrast to _.map it returns an object.
/*
它类似于map,但是这用于对象。转换每个属性的值。
*/
_.mapObject = function(obj, iteratee, context) {
iteratee = cb(iteratee, context);
var keys = _.keys(obj),
length = keys.length,
results = {};
for (var index = 0; index < length; index++) {
var currentKey = keys[index];
results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
}
return results;// 返回新对象
}; // Convert an object into a list of `[key, value]` pairs.
/*
把一个对象转变为一个[key, value]形式的数组
*/
_.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;
}; // Invert the keys and values of an object. The values must be serializable.
/*
返回一个object副本,使其键(keys)和值(values)对换
*/
_.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;
}; // Return a sorted list of the function names available on the object.
// Aliased as `methods`.
/*
返回一个对象里所有的方法名, 而且是已经排序的 — 也就是说, 对象里每个方法(属性值是一个函数)的名称
*/
_.functions = _.methods = function(obj) {
var names = [];
for (var key in obj) {
if (_.isFunction(obj[key])) names.push(key);
}
return names.sort();
}; // An internal function for creating assigner functions.
var createAssigner = function(keysFunc, defaults) {
return function(obj) {
var length = arguments.length;
if (defaults) obj = Object(obj);
if (length < 2 || obj == null) return obj;// 如果参数个数小于2,或者obj为null,返回null
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 (!defaults || obj[key] === void 0) obj[key] = source[key];// 若source中没有key属性才会复制,相同属性key不会覆盖
}
}
return obj;
};
}; // Extend a given object with all the properties in passed-in object(s).
/*
复制source对象中的所有属性覆盖到destination对象上,并且返回 destination 对象. 不会覆盖
*/
_.extend = createAssigner(_.allKeys); // Assigns a given object with all the own properties in the passed-in object(s).
// (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
/*
类似于 extend, 但只复制自己的属性覆盖到目标对象。
*/
_.extendOwn = _.assign = createAssigner(_.keys); // Returns the first key on an object that passes a predicate test.
/*
类似findIndex(),返回符合predicate的key
*/
_.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;
}
}; // Internal pick helper function to determine if `obj` has key `key`.
/*
判断key是obj的自身属性(或继承属性)
*/
var keyInObj = function(value, key, obj) {
return key in obj;
}; // Return a copy of the object only containing the whitelisted properties.
/*
返回一个object副本,只过滤出keys(有效的键组成的数组)参数指定的属性值。或者接受一个判断函数,指定挑选哪个key。、
restArgs()把keys及后面的参数变为一个数组
*/
_.pick = restArgs(function(obj, keys) {
var result = {}, iteratee = keys[0];
if (obj == null) return result;
if (_.isFunction(iteratee)) {// 如果此函数的第二个参数是一个函数
if (keys.length > 1) iteratee = optimizeCb(iteratee, keys[1]);// 如果后面还有第三个参数,作为itetratee的参数传入,变成一个高阶函数
keys = _.allKeys(obj);
} else {// 第二个参数不是一个函数
iteratee = keyInObj;// 就把上面的keyInObj传给他
keys = flatten(keys, false, false);
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;// 如果是函数,则执行函数;不是函数,执行 key in obj
}
return result;
}); // Return a copy of the object without the blacklisted properties.
/*
返回一个object副本,只过滤出除去keys(有效的键组成的数组)参数指定的属性值。 或者接受一个判断函数,指定忽略哪个key。
*/
_.omit = restArgs(function(obj, keys) {
var iteratee = keys[0], context;
if (_.isFunction(iteratee)) {
iteratee = _.negate(iteratee);// 返回iteratee的否定版本
if (keys.length > 1) context = keys[1];
} else {
keys = _.map(flatten(keys, false, false), String);
iteratee = function(value, key) {
return !_.contains(keys, key);
};
}
return _.pick(obj, iteratee, context);
}); // Fill in a given object with default properties.
_.defaults = createAssigner(_.allKeys, true); // Creates an object that inherits from the given prototype object.
// If additional properties are provided then they will be added to the
// created object.
/*
创建具有给定原型的新对象, 可选附加props 作为 own的属性。 基本上,和Object.create一样, 但是没有所有的属性描述符。
*/
_.create = function(prototype, props) {
var result = baseCreate(prototype);// 原型继承
if (props) _.extendOwn(result, props);
return result;
}; // Create a (shallow-cloned) duplicate of an object.
/*
创建 一个浅复制(浅拷贝)的克隆object。任何嵌套的对象或数组都通过引用拷贝,不会复制。
*/
_.clone = function(obj) {
if (!_.isObject(obj)) return obj;
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
}; // Invokes interceptor with the obj, and then returns obj.
// The primary purpose of this method is to "tap into" a method chain, in
// order to perform operations on intermediate results within the chain.
/*
用 object作为参数来调用函数interceptor,然后返回object。这种方法的主要意图是作为函数链式调用 的一环, 为了对此对象执行操作并返回对象本身。
*/
_.tap = function(obj, interceptor) {
interceptor(obj);
return obj;
}; // Returns whether an object has a given set of `key:value` pairs.
/*
告诉你properties中的键和值是否包含在object中。
*/
_.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;
}; // Internal recursive comparison function for `isEqual`.
/*
内部比较函数,判断a,b是否相等??????????????????????????????????????????????????????????????????????????????
*/
var eq, deepEq;
eq = function(a, b, aStack, bStack) {
// Identical objects are equal. `0 === -0`, but they aren't identical.
// See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
if (a === b) return a !== 0 || 1 / a === 1 / b;// 0 === -0
// A strict comparison is necessary because `null == undefined`.
// 针对null == undefined ,"==="是必须的
if (a == null || b == null) return a === b;
// `NaN`s are equivalent, but non-reflexive.
// NaN
if (a !== a) return b !== b;
// Exhaust primitive checks
var type = typeof a;
if (type !== 'function' && type !== 'object' && typeof b != 'object') return false;
return deepEq(a, b, aStack, bStack);
}; // Internal recursive comparison function for `isEqual`.
deepEq = function(a, b, aStack, bStack) {
// Unwrap any wrapped objects.
if (a instanceof _) a = a._wrapped;
if (b instanceof _) b = b._wrapped;
// Compare `[[Class]]` names.
// 判断a,b的类型,并且a,b类型一定相等
var className = toString.call(a);
if (className !== toString.call(b)) return false;
switch (className) {
// Strings, numbers, regular expressions, dates, and booleans are compared by value.
case '[object RegExp]':
// RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
case '[object String]':
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
// equivalent to `new String("5")`.
return '' + a === '' + b;
case '[object Number]':
// `NaN`s are equivalent, but non-reflexive.
// Object(NaN) is equivalent to NaN.
if (+a !== +a) return +b !== +b;
// An `egal` comparison is performed for other numeric values.
return +a === 0 ? 1 / +a === 1 / b : +a === +b;
case '[object Date]':
case '[object Boolean]':
// Coerce dates and booleans to numeric primitive values. Dates are compared by their
// millisecond representations. Note that invalid dates with millisecond representations
// of `NaN` are not equivalent.
return +a === +b;
case '[object Symbol]':
return SymbolProto.valueOf.call(a) === SymbolProto.valueOf.call(b);
} var areArrays = className === '[object Array]';
if (!areArrays) {// 如果不是数组
if (typeof a != 'object' || typeof b != 'object') return false; // Objects with different constructors are not equivalent, but `Object`s or `Array`s
// from different frames are.
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;
}
}
// Assume equality for cyclic structures. The algorithm for detecting cyclic
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. // Initializing stack of traversed objects.
// It's done here since we only need them for objects and arrays comparison.
aStack = aStack || [];
bStack = bStack || [];
var length = aStack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
if (aStack[length] === a) return bStack[length] === b;
} // Add the first object to the stack of traversed objects.
aStack.push(a);
bStack.push(b); // Recursively compare objects and arrays.
if (areArrays) {// 如果是数组
// Compare array lengths to determine if a deep comparison is necessary.
length = a.length;
if (length !== b.length) return false;// 如果长度不等,直接pass
// Deep compare the contents, ignoring non-numeric properties.
while (length--) {
if (!eq(a[length], b[length], aStack, bStack)) return false;// 比较数组中的每一项
}
} else {// 如果不是,深度比较对象
// Deep compare objects.
var keys = _.keys(a), key;
length = keys.length;
// Ensure that both objects contain the same number of properties before comparing deep equality.
if (_.keys(b).length !== length) return false;// 如果key的长度不等,直接pass
while (length--) {
// Deep compare each member
key = keys[length];
if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
}
}
// Remove the first object from the stack of traversed objects.
aStack.pop();
bStack.pop();
return true;
}; // Perform a deep comparison to check if two objects are equal.
/*
执行两个对象之间的优化深度比较,确定他们是否应被视为相等。
*/
_.isEqual = function(a, b) {
return eq(a, b);
}; // Is a given array, string, or object empty?
// An "empty" object has no enumerable own-properties.
/*
判断是否为空
*/
_.isEmpty = function(obj) {
if (obj == null) return true;
// 有length的类型,直接判断length属性是否为0
if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;
return _.keys(obj).length === 0;
}; // Is a given value a DOM element?
/*
如果object是一个DOM元素,返回true。
*/
_.isElement = function(obj) {
return !!(obj && obj.nodeType === 1);
}; // Is a given value an array?
// Delegates to ECMA5's native Array.isArray
/*
判断是否是数组类型
*/
_.isArray = nativeIsArray || function(obj) {
return toString.call(obj) === '[object Array]';
}; // Is a given variable an object?
/*
判断是不是对象
*/
_.isObject = function(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;// !!排除null
}; // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError, isMap, isWeakMap, isSet, isWeakSet.
/*
定义各个类型判断的函数
*/
_.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error', 'Symbol', 'Map', 'WeakMap', 'Set', 'WeakSet'], function(name) {
_['is' + name] = function(obj) {
return toString.call(obj) === '[object ' + name + ']';
};
}); // Define a fallback version of the method in browsers (ahem, IE < 9), where
// there isn't any inspectable "Arguments" type.
/*
判断是否是arguments
*/
if (!_.isArguments(arguments)) {
_.isArguments = function(obj) {
return _.has(obj, 'callee');
};
} // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
// IE 11 (#1621), Safari 8 (#1929), and PhantomJS (#2236).
var nodelist = root.document && root.document.childNodes;
if (typeof /./ != 'function' && typeof Int8Array != 'object' && typeof nodelist != 'function') {
_.isFunction = function(obj) {
return typeof obj == 'function' || false;
};
} // Is a given object a finite number?
/*
判断是否有限
*/
_.isFinite = function(obj) {
return !_.isSymbol(obj) && isFinite(obj) && !isNaN(parseFloat(obj));
}; // Is the given value `NaN`?
_.isNaN = function(obj) {
return _.isNumber(obj) && isNaN(obj);
}; // Is a given value a boolean?
_.isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
}; // Is a given value equal to null?
_.isNull = function(obj) {
return obj === null;
}; // Is a given variable undefined?
_.isUndefined = function(obj) {
return obj === void 0;
}; // Shortcut function for checking if an object has a given property directly
// on itself (in other words, not on a prototype).
/*
判断obj是否自身而不是在原型链中拥有key
*/
_.has = function(obj, key) {
return obj != null && hasOwnProperty.call(obj, key);
};

小结

1.访问实例原型

var constructor = obj.constructor;
var proto = _.isFunction(constructor) && constructor.prototype || ObjProto;

2.判断是否有限

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

underscore.js源码解析【对象】的更多相关文章

  1. underscore.js源码解析(五)—— 完结篇

    最近公司各种上线,所以回家略感疲惫就懒得写了,这次我准备把剩下的所有方法全部分析完,可能篇幅过长...那么废话不多说让我们进入正题. 没看过前几篇的可以猛戳这里: underscore.js源码解析( ...

  2. underscore.js源码解析(四)

    没看过前几篇的可以猛戳这里: underscore.js源码解析(一) underscore.js源码解析(二) underscore.js源码解析(三) underscore.js源码GitHub地 ...

  3. underscore.js源码解析(三)

    最近工作比较忙,做不到每周两篇了,周末赶着写吧,上篇我针对一些方法进行了分析,今天继续. 没看过前两篇的可以猛戳这里: underscore.js源码解析(一) underscore.js源码解析(二 ...

  4. underscore.js源码解析(二)

    前几天我对underscore.js的整体结构做了分析,今天我将针对underscore封装的方法进行具体的分析,代码的一些解释都写在了注释里,那么废话不多说进入今天的正文. 没看过上一篇的可以猛戳这 ...

  5. underscore.js源码解析(一)

    一直想针对一个框架的源码好好的学习一下编程思想和技巧,提高一下自己的水平,但是看过一些框架的源码,都感觉看的莫名其妙,看不太懂,最后找到这个underscore.js由于这个比较简短,一千多行,而且读 ...

  6. underscore.js源码解析【'_'对象定义及内部函数】

    (function() { // Baseline setup // -------------- // Establish the root object, `window` (`self`) in ...

  7. underscore.js源码解析【函数】

    // Function (ahem) Functions // ------------------ // Determines whether to execute a function as a ...

  8. underscore.js源码解析【数组】

    // Array Functions // --------------- // Get the first element of an array. Passing **n** will retur ...

  9. underscore.js源码解析【集合】

    // Collection Functions // -------------------- // The cornerstone, an `each` implementation, aka `f ...

随机推荐

  1. day 32 JavaScript

    1.1. JavaScript介绍 HTML:定义网页的结构 CSS:美化网页 JavaScript:实现用户交互: 1.1.2 JavaScript特点 n  安全性较高 n  跨平台,兼容性好 1 ...

  2. Mysql 提升大数据表的拷贝效率

    工作上会经常遇到量级比较大的数据表  :场景: 该数据表需要进行alter操作 比如增加一个字段,减少一个字段. 这个在一个几万级别数据量的数据表可以直接进行alter表操作,但是要在一个接近1000 ...

  3. Idea+maven+testNG+Selenium+ReportNG自动化框架搭建

    1.Idea创建一个空的Maven项目 创建后默认项目目录如图所示 2.配置pom.xml文件 <?xml version="1.0" encoding="UTF- ...

  4. linux resin 基本站点配置

    进入配置文件目录: [root@linuxidc resin-]# cd /usr/local/resin/conf/ 查看都有哪些配置文件: [root@linuxidc conf]# ls app ...

  5. 四 分析easyswoole源码(启动服务&Cache组件原理)

    前文提到的在系统设置Cache组件 Cache::getInstance()的时候,会去调用processManager去创建Cache的进程,然后以管道通信的方式进行设置缓存和获取缓存. Cache ...

  6. AutoCAD开发5--批量修改dwg文件

    Dim files, path, filename path = ThisDrawing.Utility.GetString(True, "输入dwg文件所在路径:") 'dwg文 ...

  7. sqlserver删除临时表中的数据

    select distinct * into #tmptable from tablename drop table tablename select * into tablename from #t ...

  8. C#List源码

    List // C# 源码 public class List<T> : IList<T>, System.Collections.IList, IReadOnlyList&l ...

  9. centos7 安装搜狗输入法

    1.root权限,卸载 ibus : yum remove ibus 2.加入EPEL源   sudo yum install epel-release 3.添加mosquito-myrepo源 su ...

  10. APP微信支付报错《商户号该产品权限未开通,请前往商户平台>产品中心检查后重试》

    问题 最近项目使用MUI,HBuilder.开发打包H5的app 在开发H5 plus支付的时候,遇到以下问题: App微信支付调官方的统一下单接口返回错误信息 {return_msg=商户号该产品权 ...