学习jquery源码,我主要是通过妙味视频上学习的。这里将所有的源码分析,还有一些自己弄懂过程中的方法及示例整理出来,供大家参考。
我用的jquery v2.0.3版本。
var rootjquery, readylist, core_strundefined = typeof undefined, location = window.location, document = window.document, docelem = document.documentelement, _jquery = window.jquery, _$ = window.$, class2type = {}, core_deletedids = [], core_version = "2.0.3", core_concat = core_deletedids.concat, core_push = core_deletedids.push, core_slice = core_deletedids.slice, core_indexof = core_deletedids.indexof, core_tostring = class2type.tostring, core_hasown = class2type.hasownproperty, core_trim = core_version.trim, jquery = function( selector, context ) { // the jquery object is actually just the init constructor 'enhanced' return new jquery.fn.init( selector, context, rootjquery ); }, core_pnum = /[+-]?(?:\d*\.|)\d+(?:[ee][+-]?\d+|)/.source, // 匹配非空字符 core_rnotwhite = /\s+/g, //匹配html标签或#id,例如<div>或#top rquickexpr = /^(?:\s*(<[\w\w]+>)[^>]*|#([\w-]*))$/, // 匹配<p></p>类似的空标签 rsingletag = /^<(\w+)\s*/?>(?:</\1>|)$/, // 匹配-ms- rmsprefix = /^-ms-/, // 匹配带-的小写数字 rdashalpha = /-([\da-z])/gi, // 将字符串转换成大写 fcamelcase = function( all, letter ) { return letter.touppercase(); }, // the ready event handler and self cleanup method completed = function() { document.removeeventlistener( "domcontentloaded", completed, false ); window.removeeventlistener( "load", completed, false ); jquery.ready(); };
正则表达式的分析:
rquickexpr = /^(?:\s*(<[\w\w]+>)[^>]*|#([\w-]*))$/,
解析: 判断是否为html标签或#id,例如<div>或#top
x|y 表示匹配x或者y
这里可以分为两个部分来看^(?:\s(<[\w\w]+>)[^>]和 #([\w-]))$
1、^(?:\s(<[\w\w]+>)[^>]
?: (?:pattern)匹配pattern但不获取匹配结果,也就是说这是一个非获取匹配,不进行存储供以后使用。例如“industr(?:y|ies)”就是一个比“industry|industries”更简略的表达式。
\s 匹配任何空白字符,包括空格、制表符、换页符等等,零次或者多次。
[\w\w]+ 匹配于'[a-za-z0-9_]'或[^a-za-z0-9_]' 一次或多次
(<[\w\w]+>) 匹配的用<>包含的字符串,如<li>
2、#([\w-]*))$
匹配结尾带上#号的任意字符,包括下划线与-
rsingletag = /^<(\w+)\s*/?>(?:</\1>|)$/
\1表示跟第一个()中的内容匹配。<p></p>匹配,<li></p>不匹配