var Zepto = (function() { functionZ(dom, selector) { var i, len = dom ? dom.length : 0 for (i = 0; i < len; i++) this[i] = dom[i] this.length = len this.selector = selector || '' } // `$.zepto.Z` swaps out the prototype of the given `dom` array // of nodes with `$.fn` and thus supplying all the Zepto functions // to the array. This method can be overridden in plugins. zepto.Z = function(dom, selector) { returnnew Z(dom, selector) } zepto.init = function(selector, context) { // ... return zepto.Z(dom, selector) } // `$` will be the base `Zepto` object. When calling this // function just call `$.zepto.init, which makes the implementation // details of selecting nodes and creating Zepto collections // patchable in plugins. $ = function(selector, context) { return zepto.init(selector, context) } zepto.Z.prototype = Z.prototype = $.fn $.zepto = zepto return $ })()
4.2 zepto.Z和Z对象
这里有一个关键的对象zepto.Z,返回Z对象实例
1 2 3 4 5 6
functionZ(dom, selector) { var i, len = dom ? dom.length : 0 for (i = 0; i < len; i++) this[i] = dom[i] this.length = len this.selector = selector || '' }
function Z(dom, selector) { var i, len = dom ? dom.length : 0 for (i = 0; i < len; i++) this[i] = dom[i] this.length = len this.selector = selector || '' }
// 观察递归实现拷贝 functionextend(target, source, deep) { for (key in source) { if (deep && (isPlainObject(source[key]) || isArray(source[key]))) { if (isPlainObject(source[key]) && !isPlainObject(target[key])){ target[key] = {} } if (isArray(source[key]) && !isArray(target[key])){ target[key] = [] } extend(target[key], source[key], deep) } elseif (source[key] !== undefined) { target[key] = source[key] } } }
// Copy all but undefined properties from one or more // objects to the `target` object. $.extend = function(target) { // target 如果是布尔值则第二个参数是目标对象 var deep, args = slice.call(arguments, 1) if (typeof target == 'boolean') { deep = target target = args.shift() } // 目标对象只有一个,源对象可以有多个 args.forEach(function(arg) { extend(target, arg, deep) }) // 即使传入时是布尔值,运行后已经被替换目标对象 return target }
$.each = function(elements, callback){ var i, key if (likeArray(elements)) { for (i = 0; i < elements.length; i++) if (callback.call(elements[i], i, elements[i]) === false) return elements } else { for (key in elements) if (callback.call(elements[key], key, elements[key]) === false) return elements }