Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

装饰者模式在zepto源码中的应用 #7

Open
luoway opened this issue Mar 17, 2019 · 0 comments
Open

装饰者模式在zepto源码中的应用 #7

luoway opened this issue Mar 17, 2019 · 0 comments

Comments

@luoway
Copy link
Owner

luoway commented Mar 17, 2019

zepto是一个类似jQuery的JS工具方法库。

在MV*框架出现之前,JavaScript主要用于与DOM交互,jQuery、zepto是这方面的常用JS库,二者的基本用法形如:

$('div').each(fn)
$.each($('div'), fn)

在阅读zepto源码过程中,困扰我的一个问题是:

源码中既有给zepto对象属性赋值,又有给$函数的属性赋值,二者概念上有什么区别?

源码中$与zepto的关系是

var $ = function(selector, context){
    return zepto.init(selector, context)
}

源码中zepto的属性方法可以枚举如下

  • zepto.matches(element, selector)

    在DOM节点element中查找以selector为选择器的元素是否存在

  • zepto.fragment(html, name, properties)

    根据html字符串生成DOM节点

  • zepto.Z(dom, selector)

    返回构造函数Z的一个实例,实例为一个类似dom数组的伪数组对象

  • zepto.isZ(object)

    判断对象是否为Z实例

  • zepto.init(selector, context)

    返回Z实例

  • zepto.qsa(element, selector)

    element.querySelectorAll 的兼容性实现

以及uniqdeserializeValue两个挂在其上的工具函数。

构造函数Z源码:

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 || ''
}

没有形如Z.prototype.fn=funcion(){}的定义原型方法的代码。

但找到了

zepto.Z.prototype = Z.prototype = $.fn

$.fn是Z的原型,Z的实例可以通过原型链访问$.fn上的属性方法

$、zepto、Z三者的关系是

  • $() == zepto.init() => new Z() ,$是一个包裹zepto.init的函数,zepto.init返回Z的实例

  • new Z() 可以访问$.fn

在$扩展时,zepto对象、构造函数Z保持不变。

因此$是zepto的装饰者,实现了增强功能而不改变zepto及内部代码的逻辑。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant