Zepto 框架源码解析一(结构篇)

Zepto是一个面向高级浏览器的JavaScript框架的,并实现JQuery的大部分API,尤其针对手机上web开发(流量金贵,JQ又太重了),因此选择Zepto.js一个非常不错的选择!

如果要真正去了解一个框架,去读其源码还是最直接的方式 ,本系列会根绝我对zepto源码的理解,对每个功能模块逐个解析。

总体架构:

 1 var Zepto = (function() {
 2   zepto.Z = function(dom, selector) {
 3     dom = dom || []
 4     dom.__proto__ = arguments.callee.prototype
 5     dom.selector = selector || ''
 6     return dom
 7   }
 8  zepto.init = function(selector, context) {
 9     // If nothing given, return an empty Zepto collection
10     if (!selector) return zepto.Z()
11     // If a function is given, call it when the DOM is ready
12     else if (isFunction(selector)) return $(document).ready(selector)
13     // If a Zepto collection is given, juts return it
14     else if (zepto.isZ(selector)) return selector
15     else {
16       var dom
17       // normalize array if an array of nodes is given
18       if (isArray(selector)) dom = compact(selector)
19       // if a JavaScript object is given, return a copy of it
20       // this is a somewhat peculiar option, but supported by
21       // jQuery so we'll do it, too
22       else if (isPlainObject(selector))
23         dom = [$.extend({}, selector)], selector = null
24       // wrap stuff like `document` or `window`
25       else if (elementTypes.indexOf(selector.nodeType) >= 0 || selector === window)
26         dom = [selector], selector = null
27       // If it's a html fragment, create nodes from it
28       else if (fragmentRE.test(selector))
29         dom = zepto.fragment(selector.trim(), RegExp.$1), selector = null
30       // If there's a context, create a collection on that context first, and select
31       // nodes from there
32       else if (context !== undefined) return $(context).find(selector)
33       // And last but no least, if it's a CSS selector, use it to select nodes.
34       else dom = zepto.qsa(document, selector)
35       // create a new Zepto collection from the nodes found
36       return zepto.Z(dom, selector)
37     }
38   }
39   $ = function(selector, context){
40     return zepto.init(selector, context)
41   }
42  ... 代码
43 
44  zepto.Z.prototype = $.fn
45 
46   // Export internal API functions in the `$.zepto` namespace
47   zepto.camelize = camelize
48   zepto.uniq = uniq
49   $.zepto = zepto
50 
51   return $
52 })()
53 
54 // If `$` is not yet defined, point it to `Zepto`
55 window.Zepto = Zepto
56 '$' in window || (window.$ = Zepto)
57 ;

当我们用Zepto来获取一个元素的时候比如($("#zepto")),具体步骤如下:

  1. 执行zepto.init
  2. 获取这个元素  ,最后返回一个数组 然后执行 
    zepto.Z(dom, selector)
  3. 将数组化后的节点列表的__proto__指向zepto.Z.prototype 注意到zepto.Z.prototype = $.fn ,$.fn下的所有方法都挂在了zepto.Z的prototype下   也就是说$("#zepto") 已经拥有了$.fn 的所有方法 
  4. 返回数组

大致流程就这么简单,其实和jQ的执行流程是非常相似的    接下来是事件篇 尽情期待。。。

原文地址:https://www.cnblogs.com/qgd87/p/3300980.html