资讯专栏INFORMATION COLUMN

jQuery3.3.1源码阅读(一)

王晗 / 2076人阅读

摘要:入口结构具体代码抽离结构如下涉及到的知识解析函数时的规则函数定义和函数表达式闭包解析函数的规则解析器会在遇到时将其认为是函数定义而非函数表达式函数定义和函数表达式函数定义函数表达式闭包闭包函数中的函数,本质是指作用域内的作用域闭包举例综合以

1.入口结构

</>复制代码

  1. ( function( global, factory ) {
  2. "use strict";
  3. if ( typeof module === "object" && typeof module.exports === "object" ) {
  4. module.exports = global.document ? factory( global, true ) :
  5. function( w ) {
  6. if ( !w.document ) {
  7. throw new Error( "jQuery requires a window with a document" );
  8. }
  9. return factory( w );
  10. };
  11. } else {
  12. factory( global );
  13. }
  14. } )(
  15. typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
  16. //具体代码
  17. }

抽离结构如下:

</>复制代码

  1. ( function() { })()

涉及到的知识

js解析函数时的规则

函数定义和函数表达式

js闭包

js解析函数的规则

js解析器会在遇到function时将其认为是函数定义而非函数表达式

函数定义和函数表达式

函数定义:function test(){ }

函数表达式:let test = function(){ }

js闭包

闭包:函数中的函数,本质是指作用域内的作用域

</>复制代码

  1. //闭包举例
  2. function f(){
  3. var a = 2;
  4. function g(){
  5. console.log(a)
  6. };
  7. return g;
  8. }
  9. f()();

综合以上的内容,再来看一下刚才抽离出来的代码

</>复制代码

  1. (function(){ })()

第一个括号有两个作用:

让js解析器把后面的function当作函数表达式而不是函数定义

形成一个作用域,类似在上面闭包例子中的f函数

第二个括号

触发函数并传参

2.第二个括号内的参数有哪些?

</>复制代码

  1. (typeof window !== "undefined" ? window : this, function( window, noGlobal ) { })

第一个参数是判断环境,传入全局对象

第二个参数是确定环境后具体执行的代码

3.第一个括号内的函数做了什么?

</>复制代码

  1. ( function( global, factory ) {
  2. "use strict";
  3. //判断是不是在commonjs环境下,如果是就执行以下代码
  4. if ( typeof module === "object" && typeof module.exports === "object" ) {
  5. //判断是否支持global.document
  6. module.exports = global.document ?
  7. factory( global, true ) :
  8. function( w ) {
  9. //不支持global.document时报错
  10. if ( !w.document ) {
  11. throw new Error( "jQuery requires a window with a document" );
  12. }
  13. //报错后返回jquery(w)
  14. return factory( w );
  15. };
  16. } else {
  17. //windows环境下执行这个代码
  18. factory( global );
  19. }
  20. } )

4.判断完环境后通过:factory( global );跳转到第二个括号的第二个参数内执行具体的内容

</>复制代码

  1. //整体的结构抽离如下
  2. function( window, noGlobal ) {
  3. "use strict";
  4. //具体的jquery内部代码
  5. if ( !noGlobal ) {
  6. //window下可以用以下方式调用
  7. window.jQuery = window.$ = jQuery;
  8. }
  9. return jQuery;
  10. }

5.进入函数后,先定义了一些变量,函数和对象(可以跳过先看下面的内容)

</>复制代码

  1. //定义了一些变量和方法
  2. var arr = [];
  3. var document = window.document;
  4. var getProto = Object.getPrototypeOf;
  5. //数组方法简写
  6. var slice = arr.slice;
  7. var concat = arr.concat;
  8. var push = arr.push;
  9. var indexOf = arr.indexOf;
  10. //对象方法简写
  11. var class2type = {};
  12. var toString = class2type.toString;
  13. var hasOwn = class2type.hasOwnProperty;
  14. var fnToString = hasOwn.toString;
  15. var ObjectFunctionString = fnToString.call( Object );
  16. var support = {};
  17. //定义函数
  18. var isFunction = function isFunction( obj ) {
  19. return typeof obj === "function" && typeof obj.nodeType !== "number";
  20. };
  21. var isWindow = function isWindow( obj ) {
  22. return obj != null && obj === obj.window;
  23. };
  24. function DOMEval( code, doc, node ) {
  25. doc = doc || document;
  26. var i,
  27. script = doc.createElement( "script" );
  28. script.text = code;
  29. if ( node ) {
  30. for ( i in preservedScriptAttributes ) {
  31. if ( node[ i ] ) {
  32. script[ i ] = node[ i ];
  33. }
  34. }
  35. }
  36. doc.head.appendChild( script ).parentNode.removeChild( script );
  37. }
  38. function toType( obj ) {
  39. if ( obj == null ) {
  40. return obj + "";
  41. }
  42. // Support: Android <=2.3 only (functionish RegExp)
  43. return typeof obj === "object" || typeof obj === "function" ?
  44. class2type[ toString.call( obj ) ] || "object" :
  45. typeof obj;
  46. }
  47. //定义对象
  48. var preservedScriptAttributes = {
  49. type: true,
  50. src: true,
  51. noModule: true
  52. };

6.定义完上面的内容后,jQuery内部进行new对象,使得简化使用操作

</>复制代码

  1. var version = "3.3.1",
  2. //在这里jquery通过new新生成了对象简化了使用时的操作
  3. jQuery = function( selector, context ) {
  4. return new jQuery.fn.init( selector, context );
  5. },

7.new新对象时,jQuery.fn是什么?

</>复制代码

  1. jQuery.fn = jQuery.prototype = {
  2. jquery: version,
  3. constructor: jQuery,
  4. length: 0,
  5. toArray: function() {
  6. return slice.call( this );
  7. },
  8. get: function( num ) {
  9. if ( num == null ) {
  10. return slice.call( this );
  11. }
  12. return num < 0 ? this[ num + this.length ] : this[ num ];
  13. },
  14. pushStack: function( elems ) {
  15. var ret = jQuery.merge( this.constructor(), elems );
  16. ret.prevObject = this;
  17. return ret;
  18. },
  19. each: function( callback ) {
  20. return jQuery.each( this, callback );
  21. },
  22. map: function( callback ) {
  23. return this.pushStack( jQuery.map( this, function( elem, i ) {
  24. return callback.call( elem, i, elem );
  25. } ) );
  26. },
  27. slice: function() {
  28. return this.pushStack( slice.apply( this, arguments ) );
  29. },
  30. first: function() {
  31. return this.eq( 0 );
  32. },
  33. last: function() {
  34. return this.eq( -1 );
  35. },
  36. eq: function( i ) {
  37. var len = this.length,
  38. j = +i + ( i < 0 ? len : 0 );
  39. return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] );
  40. },
  41. end: function() {
  42. return this.prevObject || this.constructor();
  43. },
  44. push: push,
  45. sort: arr.sort,
  46. splice: arr.splice
  47. }

总结:看这部分源码可以知道jQuery.fn就是jquery的原型对象

8.jQuery.fn.init( selector, context )具体做了什么?

</>复制代码

  1. //selector 选择器,可能是DOM对象、html字符串、jQuery对象
  2. //context 选择器选择的范围
  3. //rootjQuery == $(document);
  4. init = jQuery.fn.init = function( selector, context, root ) {
  5. var match, elem;
  6. // 没有传选择器直接返回
  7. if ( !selector ) {
  8. return this;
  9. }
  10. root = root || rootjQuery;
  11. // 选择器传入的是字符串
  12. if ( typeof selector === "string" ) {
  13. if ( selector[ 0 ] === "<" &&
  14. selector[ selector.length - 1 ] === ">" &&
  15. selector.length >= 3 ) {
  16. match = [ null, selector, null ];
  17. } else {
  18. match = rquickExpr.exec( selector );
  19. }
  20. if ( match && ( match[ 1 ] || !context ) ) {
  21. // HANDLE: $(html) -> $(array)
  22. if ( match[ 1 ] ) {
  23. context = context instanceof jQuery ? context[ 0 ] : context;
  24. jQuery.merge( this, jQuery.parseHTML(
  25. match[ 1 ],
  26. context && context.nodeType ? context.ownerDocument || context : document,
  27. true
  28. ) );
  29. // HANDLE: $(html, props)
  30. if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) {
  31. for ( match in context ) {
  32. // Properties of context are called as methods if possible
  33. if ( isFunction( this[ match ] ) ) {
  34. this[ match ]( context[ match ] );
  35. // ...and otherwise set as attributes
  36. } else {
  37. this.attr( match, context[ match ] );
  38. }
  39. }
  40. }
  41. return this;
  42. // HANDLE: $(#id)
  43. } else {
  44. elem = document.getElementById( match[ 2 ] );
  45. if ( elem ) {
  46. // Inject the element directly into the jQuery object
  47. this[ 0 ] = elem;
  48. this.length = 1;
  49. }
  50. return this;
  51. }
  52. // HANDLE: $(expr, $(...))
  53. } else if ( !context || context.jquery ) {
  54. return ( context || root ).find( selector );
  55. // HANDLE: $(expr, context)
  56. // (which is just equivalent to: $(context).find(expr)
  57. } else {
  58. return this.constructor( context ).find( selector );
  59. }
  60. // HANDLE: $(DOMElement)
  61. } else if ( selector.nodeType ) {
  62. this[ 0 ] = selector;
  63. this.length = 1;
  64. return this;
  65. // HANDLE: $(function)
  66. // Shortcut for document ready
  67. } else if ( isFunction( selector ) ) {
  68. return root.ready !== undefined ?
  69. root.ready( selector ) :
  70. // Execute immediately if ready is not present
  71. selector( jQuery );
  72. }
  73. return jQuery.makeArray( selector, this );
  74. };

整体看摸不着头脑,抽离结构如下:

</>复制代码

  1. init = jQuery.fn.init = function( selector, context, root ) {
  2. if ( typeof selector === "string" ) {
  3. //选择器类型是字符
  4. }else if( selector.nodeType ){
  5. //选择器类型是节点
  6. }else if( jQuery.isFunction( selector ) ){
  7. //简化$(document).ready(function(){});
  8. }
  9. //返回结果。
  10. return jQuery.makeArray( selector, this );
  11. }

抽离完了要想理解这些内容,首先来看看jquery到底支持哪些选择器selector?

</>复制代码

  1. 1.$(document)
  2. 2.$("
    ")
  3. 3.$(".div")
  4. 4.$("#test")
  5. 5.$(function(){})
  6. 6.$("input:radio", document.forms[0]);
  7. 7.$("input", $("div"))
  8. 8.$()
  9. 9.$("
    ", { "class": "test" }).appendTo("body");

接着一个一个分支的看,它是如何支持这些选择器的,首先是typeof selector === "string"

</>复制代码

  1. if ( typeof selector === "string" ) {
  2. //传入的是标签类型,比如

  3. if ( selector[ 0 ] === "<" &&
  4. selector[ selector.length - 1 ] === ">" &&
  5. selector.length >= 3 ) {
  6. // 将html储存入match数组中,并与另一个分支中的正则捕获相对应
  7. match = [ null, selector, null ];
  8. } else {
  9. //放入正则进行匹配,结果类型是:[全匹配, , #id]
  10. //rquickExpr = /^(?:s*(<[wW]+>)[^>]*|#([w-]+))$/
  11. //匹配HTML标记和ID表达式
  12. match = rquickExpr.exec( selector );
  13. }
  14. // 如果match不为空,并且match[1]也就是存在
  15. if ( match && ( match[ 1 ] || !context ) ) {
  16. if ( match[ 1 ] ) {
  17. // 如果context是jQuery对象,则取其中的第一个DOM元素作为context
  18. context = context instanceof jQuery ? context[ 0 ] : context;
  19. // 将通过parseHTML处理生成的DOM对象merge进jQuery对象
  20. jQuery.merge( this, jQuery.parseHTML(
  21. match[ 1 ],
  22. //如果context存在并且是note节点,则context就是的顶级节点或自身,否则content=document
  23. context && context.nodeType ? context.ownerDocument || context : document,
  24. true
  25. ) );
  26. // HANDLE: $(html, props)
  27. if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) {
  28. for ( match in context ) {
  29. if ( isFunction( this[ match ] ) ) {
  30. this[ match ]( context[ match ] );
  31. } else {
  32. this.attr( match, context[ match ] );
  33. }
  34. }
  35. }
  36. return this;
  37. //如果是#id的形式,走这个分支进行处理
  38. } else {
  39. //通过getEle方法获得DOM对象 将match[2]传入,是因为#id的形式是在第二个捕获组里面储存的。
  40. elem = document.getElementById( match[ 2 ] );
  41. // 如果该id元素存在
  42. if ( elem ) {
  43. // 将该元素保存进jQuery对象数组当中,并设置其length值为1
  44. this[ 0 ] = elem;
  45. this.length = 1;
  46. }
  47. return this;
  48. }
  49. } else if ( !context || context.jquery ) {
  50. //如果context不存在或者context是jQuery对象
  51. //通过检测是不是有jquery属性
  52. // 进入Sizzle进行处理(复杂的选择器)
  53. return ( context || root ).find( selector );
  54. } else {
  55. //context存在并且context不是jQuery对象的情况 先调用$(context),在进入Sizzle进行处理
  56. return this.constructor( context ).find( selector );
  57. }
  58. }

接着是selector.nodeType分支

</>复制代码

  1. else if ( selector.nodeType ) {
  2.     //直接将DOM元素存入jQuery对象并设置context和length
  3.     this.context = this[0] = selector;
  4.     this.length = 1;
  5.     return this;
  6.    }

最后是jQuery.isFunction( selector )分支

</>复制代码

  1. else if ( jQuery.isFunction( selector ) ) {
  2. //简化$(document).ready(function(){});
  3.     return rootjQuery.ready( selector );
  4.   }

分析了以上的分支,把jquery的选择器分别带进去走一下流程,首先是`3.$("div")
首先进入:

</>复制代码

  1. if ( typeof selector === "string" ) {}

接着进入下面的if分支:

</>复制代码

  1. if ( match && (match[1] || !context) ) {
  2. if ( match[1] ) {
  3. context = context instanceof jQuery ? context[0] : context;
  4. jQuery.merge( this, jQuery.parseHTML(
  5.         match[1],
  6.         context && context.nodeType ? context.ownerDocument || context : document,
  7.         true
  8.       ) );
  9. }
  10. }

它进入了一个函数parseHTML()

</>复制代码

  1. jQuery.parseHTML = function( data, context, keepScripts ) {
  2. if ( typeof data !== "string" ) {
  3. return [];
  4. }
  5. if ( typeof context === "boolean" ) {
  6. keepScripts = context;
  7. context = false;
  8. }
  9. var base, parsed, scripts;
  10. if ( !context ) {
  11. if ( support.createHTMLDocument ) {
  12. context = document.implementation.createHTMLDocument( "" );
  13. base = context.createElement( "base" );
  14. base.href = document.location.href;
  15. context.head.appendChild( base );
  16. } else {
  17. context = document;
  18. }
  19. }
  20. //var rsingleTag = ( /^<([a-z][^/>:x20
  21. f]*)[x20
  22. f]*/?>(?:|)$/i );
  23. //匹配一个独立的标签
  24. parsed = rsingleTag.exec( data );
  25. scripts = !keepScripts && [];
  26. if ( parsed ) {
  27. return [ context.createElement( parsed[ 1 ] ) ];
  28. }
  29. //未通过节点的字符串,则通过创建一个div节点,将字符串置入div的innerHTML
  30. parsed = buildFragment( [ data ], context, scripts );
  31. if ( scripts && scripts.length ) {
  32. jQuery( scripts ).remove();
  33. }
  34. return jQuery.merge( [], parsed.childNodes );
  35. };

最后返回this也就是jQuery

</>复制代码

  1. return this;

再看一下4.$("#id")
首先进入:

</>复制代码

  1. if ( typeof selector === "string" ) {}

接着进入下面的else分支进行正则匹配:

</>复制代码

  1. if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
  2. //不满足
  3. }else{
  4. match = rquickExpr.exec( selector );
  5. }

匹配完了再接着进入下面的else分支进行寻找添加:

</>复制代码

  1. if ( match[1] ) {
  2. //不满足
  3. }else{
  4. elem = document.getElementById( match[2] );
  5. if ( elem ) {
  6.    // 将该元素保存进jQuery对象数组当中,并设置其length值为1
  7.    this.length = 1;
  8.     this[0] = elem;
  9.   }
  10. }

最后返回this也就是jQuery

</>复制代码

  1. return this;

今儿先看到这!!!!

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/103442.html

相关文章

  • 篇文章把本该属于你的源码天赋还给你

    摘要:一些方法不应该这样不应该漫无目的地随手拿起一分源码,试图去通读。应该这样精心挑选要阅读的源码项目。这最好是与你的编程语言你的工作内容你的兴趣所在相关的,这样才能更切实地感受到阅读源码给你带来的益处,更有动力继续。 showImg(https://segmentfault.com/img/bVbcvmm?w=785&h=525); 怎么阅读源码 没有经验的技术差底子薄的初级程序员,如何阅...

    chanjarster 评论0 收藏0
  • 精读《源码学习》

    摘要:精读原文介绍了学习源码的两个技巧,并利用实例说明了源码学习过程中可以学到许多周边知识,都让我们受益匪浅。讨论地址是精读源码学习如果你想参与讨论,请点击这里,每周都有新的主题,周末或周一发布。 1. 引言 javascript-knowledge-reading-source-code 这篇文章介绍了阅读源码的重要性,精读系列也已有八期源码系列文章,分别是: 精读《Immer.js》源...

    aboutU 评论0 收藏0
  • TiDB Binlog 源码阅读系列文章()序

    摘要:总体而言,读者需要有一定的使用经验,以及可以读懂语言程序。内容概要本篇作为源码阅读系列文章的序篇,会简单的给大家讲一下后续会讲哪些部分以及逻辑顺序,方便大家对本系列文章有整体的了解。小结本篇文章主要介绍了源码阅读系列文章的目的和规划。 作者:黄佳豪 TiDB Binlog 组件用于收集 TiDB 的 binlog,并准实时同步给下游,如 TiDB、MySQL 等。该组件在功能上类似于 ...

    whidy 评论0 收藏0

发表评论

0条评论

王晗

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<