基于Javascript原型的Zepto框架设计
2018-05-15王运倪静
王运 倪静
摘 要:随着互联网的普及,前端技术也得到了迅速发展。为了深入了解前端开发中的框架设计原理,以Zepto前端框架为例,利用Javascript原型链的相关知识,采用原生Javascript与框架对比的方法剖析了框架整体设计思路,细致分析了框架的大致架构,重构了Zepto对象原型,并封装了可能用到的所有方法。利用这种从宏观到微观的研究视角,最终呈现了一个框架的整体细致构造及其与底层原生Javascript的联系,以便于开发者熟悉框架设计原理,更好地设计出自己的框架。
关键词:Javascript;前端框架;原型;Zepto
DOI:10.11907/rjdk.172716
中图分类号:TP319
文献标识码:A 文章编号:1672-7800(2018)004-0124-03
Abstract:In order to gain a better understanding of the framework design principles in front-end development, we take the front-end framework of Zepto as an example, use Javascript prototype chain, native Javascript and frame comparison method to analyze the framework of the overall design ideas. We have detailed analysis of the framework of the general structure, reconstruct Zepto object prototype, and encapsulate all the methods that will be used. Based on the micro-to-micro perspective, we present a framework of the overall structure and its relationship with the underlying native Javascript, which help developers familiarize framework design principles to better establish their frameworks.
Key Words:Javascript; front frame; prototype; Zepto
0 引言
近几年随着前端领域的迅速发展,出现了多种类型的框架[1],目前市场上的主流框架(库)有jQuery、Vue、React与Angular等。但这几种框架的代码量太大,架构体系也比较繁琐,所以本文选取一种成熟且经典的框架,即Zepto进行分析[2]。该框架虽然出现时间较早,但作为设计框架的例子进行分析是十分适合的。首先,其架构与当前热门的jQuery很相似;其次,其代码量简短,可方便进行更透彻的分析。而框架的所有内容都是对底层知识的封装,采用原生Javascript与其对比的方法进行分析,可起到事半功倍的效果[3]。
1 Zepto简介
Zepto在5年前是一款十分热门的框架,其应用领域在于移动端,与jQuery框架十分相似。Zepto框架大量参考了jQuery的API,简化了对部分浏览器的兼容,例如IE。因此,可以说它是为移动端量身打造的[4],但其核心模块只有不到一千行的代码,相对于jQuery一万多行的代码量,其无论是分析还是编写都方便许多。……
