美文网首页
Underscore源码(5)

Underscore源码(5)

作者: ____雨歇微凉 | 来源:发表于2016-12-09 23:03 被阅读81次

    // Object Functions
    // ----------------

    // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
    var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
    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;
    
        // Constructor is a special case.
        var prop = 'constructor';
        // _.contains() 为key添加枚举属性
        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
     * 检索object拥有的所有可枚举属性的名称。
     */
    
    //
    // Retrieve the names of an object's own properties.
    // Delegates to **ECMAScript 5**'s native `Object.keys`
    _.keys = function(obj) {
        // 验证是否是obj
        if (!_.isObject(obj)) return [];
        // 如果支持原生
        if (nativeKeys) return nativeKeys(obj);
        var keys = [];
        // 枚举
        for (var key in obj) if (_.has(obj, key)) keys.push(key);
        // Ahem, IE < 9. 兼容ie9 以下。给obj添加枚举属性
        if (hasEnumBug) collectNonEnumProps(obj, keys);
        return keys;
    };
    /*——————————————————————————————————————————————————————————————————————————*/
    
    /**
     * keys
     * 检索object拥有的和继承的所有属性的名称。
     */
    
    // Retrieve all the property names of an 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;
    };
    
    /*——————————————————————————————————————————————————————————————————————————*/
    
    /**
     * values
     * 返回object对象所有的属性值。
     */
    
    // Retrieve the values of an object's properties.
    _.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;
    };
    
    /*——————————————————————————————————————————————————————————————————————————*/
    
    /**
     * mapObject
     * 它类似于map,但是这用于对象。转换每个属性的值。
     */
    
    // Returns the results of applying the iteratee to each element of the object
    // In contrast to _.map it returns an object
    _.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];
            // 目标key的值,等于自定义函数返回的key的值
            results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
        }
        return results;
    };
    /*——————————————————————————————————————————————————————————————————————————*/
    
    /**
     * pairs
     * 将对象转换为有两个值,类似键值对的数组
     */
    // Convert an object into a list of `[key, value]` pairs.
    _.pairs = function(obj) {
        var keys = _.keys(obj);
        var length = keys.length;
        var pairs = Array(length);
        for (var i = 0; i < length; i++) {
            // 将key作为第一个值,value作为第二个值
            pairs[i] = [keys[i], obj[keys[i]]];
        }
        return pairs;
    };
    
    /*——————————————————————————————————————————————————————————————————————————*/
    
    /**
     * invert
     * 返回一个object副本,使其键(keys)和值(values)对换。
     */
    // Invert the keys and values of an object. The values must be serializable.
    _.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;
    };
    
    /*——————————————————————————————————————————————————————————————————————————*/
    
    /**
     * functions
     * 返回一个对象中的所有方法名,只返回function
     */
    
    // 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();
    };
    
    /*——————————————————————————————————————————————————————————————————————————*/
    
    /**
     * extend
     * 合并对象,相同的属性会覆盖
     */
    // Extend a given object with all the properties in passed-in object(s).
    _.extend = createAssigner(_.allKeys);
    
    /*——————————————————————————————————————————————————————————————————————————*/
    
    /**
     * extend
     * 合并对象属性,只合并对象的属性,相同会覆盖,不包括继承
     */
    // 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)
    _.extendOwn = _.assign = createAssigner(_.keys);
    
    /*——————————————————————————————————————————————————————————————————————————*/
    
    /**
     * findKey
     * 查找对象中是否存在KEY,找不到return undefined
     */
    // Returns the first key on an object that passes a predicate test
    _.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;
        }
    };
    
    /*——————————————————————————————————————————————————————————————————————————*/
    
    /**
     * pick
     * 返回一个object副本,只过滤出keys(有效的键组成的数组)参数指定的属性值。
     */
    // Return a copy of the object only containing the whitelisted properties.
    _.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);
            // 如果不是,则判断他的key 是否在obj中
            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;
    };
    
    /*——————————————————————————————————————————————————————————————————————————*/
    
    /**
     * omit
     * 返回一个object副本,只过滤出除去keys(有效的键组成的数组)参数指定的属性值。 -> 算是反pick 找剩下的。
     */
    // Return a copy of the object without the blacklisted properties.
    _.omit = function(obj, iteratee, context) {
        if (_.isFunction(iteratee)) {
            // negate 返回自定义函数的一个否定版本
            iteratee = _.negate(iteratee);
        } else {
            var keys = _.map(flatten(arguments, false, false, 1), String);
            iteratee = function(value, key) {
                // 存在的全部取反
                return !_.contains(keys, key);
            };
        }
        // 然后再次调用pick
        return _.pick(obj, iteratee, context);
    };
    /*——————————————————————————————————————————————————————————————————————————*/
    
    /**
     * defaults
     * 填充默认参数
     */
    
    // Fill in a given object with default properties.
    _.defaults = createAssigner(_.allKeys, true);
    
    /*——————————————————————————————————————————————————————————————————————————*/
    
    /**
     * defaults
     * 创建具有给定原型的新对象, 可选附加props 作为 own的属性。 基本上,和Object.create一样, 但是没有所有的属性描述符。
     */
    // Creates an object that inherits from the given prototype object.
    // If additional properties are provided then they will be added to the
    // created object.
    _.create = function(prototype, props) {
        // 创建一个原型对象
        var result = baseCreate(prototype);
        // 将目标属性全部添加到原型上
        if (props) _.extendOwn(result, props);
        return result;
    };
    
    /*——————————————————————————————————————————————————————————————————————————*/
    
    /**
     * defaults
     * 创建 一个浅复制(浅拷贝)的克隆object。任何嵌套的对象或数组都通过引用拷贝,不会复制。
     */
    
    // Create a (shallow-cloned) duplicate of an object.
    _.clone = function(obj) {
        if (!_.isObject(obj)) return obj;
        return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
    };
    /*——————————————————————————————————————————————————————————————————————————*/
    
    /**
     * tap
     * 用 object作为参数来调用函数interceptor,然后返回object。
     */
    
    // 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.
    _.tap = function(obj, interceptor) {
        // 类似执行一个中间件函数,但是对结果不会产生任何影响
        interceptor(obj);
        return obj;
    };
    
    
    /*——————————————————————————————————————————————————————————————————————————*/
    
    /**
     * isMatch
     * Match:相同
     * 告诉你properties中的键和值是否包含在object中。
     */
    // Returns whether an object has a given set of `key:value` pairs.
    _.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];
            // 两个的键值对不相等,或者obj中没有这个key ,则返回false
            if (attrs[key] !== obj[key] || !(key in obj)) return false;
        }
        return true;
    };
    
    
    
    /*——————————————————————————————————————————————————————————————————————————*/
    
    /**
     * isEqual
     * Match:相同
     * 比较两个对象是否完全像等
     */
    // Internal recursive comparison function for `isEqual`.
    var 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).
        // 兼容 `0 === -0`,返回false
        if (a === b) return a !== 0 || 1 / a === 1 / b;
        // A strict comparison is necessary because `null == undefined`.
        // 比较 null 和 undefined
        if (a == null || b == null) return a === b;
        // Unwrap any wrapped objects.
        // 打开任何包裹物。
        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) {
            // 正则
            // 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")`.
                // toString
                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.
                // 仍然兼容0
                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;
        }
    
        // 比较数组
        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;
            // 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;
            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);
    };
    
    /*——————————————————————————————————————————————————————————————————————————*/
    /**
     * isEmpty
     * 判断是否为空,没有可枚举属性也为true
     */
    // Is a given array, string, or object empty?
    // An "empty" object has no enumerable own-properties.
    _.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;
    };
    
    /*——————————————————————————————————————————————————————————————————————————*/
    /**
     * isElement
     * 判断是否为element
     */
    // Is a given value a DOM element?
    _.isElement = function(obj) {
        return !!(obj && obj.nodeType === 1);
    };
    
    /*——————————————————————————————————————————————————————————————————————————*/
    /**
     * isArray
     * 判断是否为Array
     */
    // Is a given value an array?
    // Delegates to ECMA5's native Array.isArray
    _.isArray = nativeIsArray || function(obj) {
            // 使用toString 方法比较
            return toString.call(obj) === '[object Array]';
        };
    
    /*——————————————————————————————————————————————————————————————————————————*/
    /**
     * isObject
     * func 和 obj 都是obj
     */
    // Is a given variable an object?
    _.isObject = function(obj) {
        var type = typeof obj;
        return type === 'function' || type === 'object' && !!obj;
    };
    
    // 为这些方法添加公共函数
    // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.
    _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], 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.
    // 如果_.isArguments() 返回了false ,然后在检查里面是否有callee属性,有则为arguments
    if (!_.isArguments(arguments)) {
        _.isArguments = function(obj) {
            return _.has(obj, 'callee');
        };
    }
    
    // 兼容旧V8 & ie11 & Safari 8
    // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
    // IE 11 (#1621), and in Safari 8 (#1929).
    if (typeof /./ != 'function' && typeof Int8Array != 'object') {
        _.isFunction = function(obj) {
            return typeof obj == 'function' || false;
        };
    }
    
    // 如果object是一个有限的数字,返回true。
    // Is a given object a finite number?
    _.isFinite = function(obj) {
        return isFinite(obj) && !isNaN(parseFloat(obj));
    };
    
    // 判断是否为NaN
    // Is the given value `NaN`? (NaN is the only number which does not equal itself).
    _.isNaN = function(obj) {
        return _.isNumber(obj) && obj !== +obj;
    };
    
    // 是否为布尔值
    // Is a given value a boolean?
    _.isBoolean = function(obj) {
        return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
    };
    
    // 是否是null
    // Is a given value equal to null?
    _.isNull = function(obj) {
        return obj === null;
    };
    
    // 是否是undefined
    // Is a given variable undefined?
    _.isUndefined = function(obj) {
        return obj === void 0;
    };
    
    // 对象是否包含给定的键吗?
    // hasOwnProperty 是JavaScript中唯一一个处理属性但是不需要查找原型链的方法。
    // Shortcut function for checking if an object has a given property directly
    // on itself (in other words, not on a prototype).
    _.has = function(obj, key) {
        return obj != null && hasOwnProperty.call(obj, key);
    };
    
    // Utility Functions
    // -----------------
    
    
    // 放弃Underscore 的控制变量"_"。返回Underscore 对象的引用。
    // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
    // previous owner. Returns a reference to the Underscore object.
    _.noConflict = function() {
        root._ = previousUnderscore;
        return this;
    };
    
    // 返回与传入参数相等的值. 相当于数学里的: f(x) = x
    // Keep the identity function around for default iteratees.
    _.identity = function(value) {
        return value;
    };
    
    // 创建一个函数,这个函数 返回相同的值 用来作为_.constant的参数。
    // Predicate-generating functions. Often useful outside of Underscore.
    _.constant = function(value) {
        return function() {
            return value;
        };
    };
    
    // 返回undefined,不论传递给它的是什么参数。 可以用作默认可选的回调参数。
    _.noop = function(){};
    
    // 返回一个函数,这个函数返回任何传入的对象的key属性。
    _.property = function(key) {
        return function(obj) {
            return obj == null ? void 0 : obj[key];
        };
    };
    
    // 和_.property相反。需要一个对象,并返回一个函数,这个函数将返回一个提供的属性的值。
    // Generates a function for a given object that returns a given property.
    _.propertyOf = function(obj) {
        return obj == null ? function(){} : function(key) {
            return obj[key];
        };
    };
    
    //返回一个断言函数,这个函数会给你一个断言可以用来辨别给定的对象是否匹配attrs指定键/值属性。
    // Returns a predicate for checking whether an object has a given set of
    // `key:value` pairs.
    _.matcher = _.matches = function(attrs) {
        attrs = _.extendOwn({}, attrs);
        return function(obj) {
            // attrs 是否存在于obj
            return _.isMatch(obj, attrs);
        };
    };
    
    //调用给定的迭代函数n次,
    // Run a function **n** times.
    _.times = function(n, iteratee, context) {
        // 指定次数,否则为零
        var accum = Array(Math.max(0, n));
        iteratee = optimizeCb(iteratee, context, 1);
        // 回调函数传入index,并将返回值保存起来,最后一次返回
        for (var i = 0; i < n; i++) accum[i] = iteratee(i);
        return accum;
    };
    
    // 返回一个min 和 max之间的随机整数。如果你只传递一个参数,那么将返回0和这个参数之间的整数。
    // Return a random integer between min and max (inclusive).
    _.random = function(min, max) {
        if (max == null) {
            max = min;
            min = 0;
        }
        return min + Math.floor(Math.random() * (max - min + 1));
    };
    
    // 一个优化的方式来获得一个当前时间的整数时间戳。可用于实现定时/动画功能。
    // A (possibly faster) way to get the current timestamp as an integer.
    _.now = Date.now || function() {
            return new Date().getTime();
        };
    
    // List of HTML entities for escaping.
    var escapeMap = {
        '&': '&',
        '<': '<',
        '>': '>',
        '"': '"',
        "'": ''',
        '`': '`'
    };
    var unescapeMap = _.invert(escapeMap);
    
    // Functions for escaping and unescaping strings to/from HTML interpolation.
    var createEscaper = function(map) {
        var escaper = function(match) {
            return map[match];
        };
        // Regexes for identifying a key that needs to be escaped
        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;
        };
    };
    // 转义HTML字符串,替换&, <, >, ", ', 和 /字符。
    _.escape = createEscaper(escapeMap);
    // 相反
    _.unescape = createEscaper(unescapeMap);
    
    // 如果指定的property 的值是一个函数,那么将在object上下文内调用它;否则,返回它。如果提供默认值,并且属性不存在,那么默认值将被返回。
    // 如果设置defaultValue是一个函数,它的结果将被返回。
    // If the value of the named `property` is a function then invoke it with the
    // `object` as context; otherwise, return it.
    _.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;
    };
    
    // 为需要的客户端模型或DOM元素生成一个全局唯一的id。如果prefix参数存在, id 将附加给它。
    // Generate a unique integer id (unique within the entire client session).
    // Useful for temporary DOM ids.
    var idCounter = 0;
    _.uniqueId = function(prefix) {
        var id = ++idCounter + '';
        return prefix ? prefix + id : id;
    };
    
    // By default, Underscore uses ERB-style template delimiters, change the
    // following template settings to use alternative delimiters.
    _.templateSettings = {
        evaluate    : /<%([\s\S]+?)%>/g,
        interpolate : /<%=([\s\S]+?)%>/g,
        escape      : /<%-([\s\S]+?)%>/g
    };
    
    // When customizing `templateSettings`, if you don't want to define an
    // interpolation, evaluation or escaping regex, we need one that is
    // guaranteed not to match.
    var noMatch = /(.)^/;
    
    // Certain characters need to be escaped so that they can be put into a
    // string literal.
    var escapes = {
        "'":      "'",
        '\\':     '\\',
        '\r':     'r',
        '\n':     'n',
        '\u2028': 'u2028',
        '\u2029': 'u2029'
    };
    
    var escaper = /\\|'|\r|\n|\u2028|\u2029/g;
    
    var escapeChar = function(match) {
        return '\\' + escapes[match];
    };
    
    // JavaScript micro-templating, similar to John Resig's implementation.
    // Underscore templating handles arbitrary delimiters, preserves whitespace,
    // and correctly escapes quotes within interpolated code.
    // NB: `oldSettings` only exists for backwards compatibility.
    _.template = function(text, settings, oldSettings) {
        if (!settings && oldSettings) settings = oldSettings;
        settings = _.defaults({}, settings, _.templateSettings);
    
        // Combine delimiters into one regular expression via alternation.
        var matcher = RegExp([
                (settings.escape || noMatch).source,
                (settings.interpolate || noMatch).source,
                (settings.evaluate || noMatch).source
            ].join('|') + '|$', 'g');
    
        // Compile the template source, escaping string literals appropriately.
        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+='";
            }
    
            // Adobe VMs need the match returned to produce the correct offest.
            return match;
        });
        source += "';\n";
    
        // If a variable is not specified, place data values in local scope.
        if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
    
        source = "var __t,__p='',__j=Array.prototype.join," +
            "print=function(){__p+=__j.call(arguments,'');};\n" +
            source + 'return __p;\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, _);
        };
    
        // Provide the compiled source as a convenience for precompilation.
        var argument = settings.variable || 'obj';
        template.source = 'function(' + argument + '){\n' + source + '}';
    
        return template;
    };
    
    // 返回一个封装的对象. 在封装的对象上调用方法会返回封装的对象本身, 直道 value 方法调用为止.
    // Add a "chain" function. Start chaining a wrapped Underscore object.
    _.chain = function(obj) {
        var instance = _(obj);
        instance._chain = true;
        return instance;
    };
    
    // OOP
    // ---------------
    // If Underscore is called as a function, it returns a wrapped object that
    // can be used OO-style. This wrapper holds altered versions of all the
    // underscore functions. Wrapped objects may be chained.
    
    // Helper function to continue chaining intermediate results.
    var result = function(instance, obj) {
        return instance._chain ? _(obj).chain() : obj;
    };
    
    // Add your own custom functions to the Underscore object.
    _.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));
            };
        });
    };
    
    // Add all of the Underscore functions to the wrapper object.
    _.mixin(_);
    
    // 将原生的这几个方法也绑定在_ 上
    // Add all mutator Array functions to the wrapper.
    _.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);
        };
    });
    
    // 将原生的这几个方法也绑定在_ 上
    // Add all accessor Array functions to the wrapper.
    _.each(['concat', 'join', 'slice'], function(name) {
        var method = ArrayProto[name];
        _.prototype[name] = function() {
            return result(this, method.apply(this._wrapped, arguments));
        };
    });
    
    // Extracts the result from a wrapped and chained object.
    _.prototype.value = function() {
        return this._wrapped;
    };
    
    // Provide unwrapping proxy for some methods used in engine operations
    // such as arithmetic and JSON stringification.
    _.prototype.valueOf = _.prototype.toJSON = _.prototype.value;
    
    _.prototype.toString = function() {
        return '' + this._wrapped;
    };

    相关文章

      网友评论

          本文标题:Underscore源码(5)

          本文链接:https://www.haomeiwen.com/subject/loiupttx.html