jQuery源码分析系列 : 整体架构
query這么多年了分析都寫爛了,老早以前就拜讀過, 不過這幾年都是做移動端,一直御用zepto, 最近抽出點時間把jquery又給掃一遍 我也不會照本宣科的翻譯源碼,結合自己的實際經驗一起拜讀吧! github上最新是jquery-master,加入了AMD規范了,我就以官方最新2.0.3為準
整體架構
jQuery框架的核心就是從HTML文檔中匹配元素并對其執行操作、 例如:
$().find().css() $().hide().html('....').hide(). 復制代碼從上面的寫法上至少可以發現2個問題
分析一:jQuery的無new構建
JavaScript是函數式語言,函數可以實現類,類就是面向對象編程中最基本的概念
var aQuery = function(selector, context) {//構造函數 } aQuery.prototype = {//原型name:function(){},age:function(){} }var a = new aQuery();a.name(); 復制代碼這是常規的使用方法,顯而易見jQuery不是這樣玩的 jQuery沒有使用new運行符將jQuery顯示的實例化,還是直接調用其函數 按照jQuery的抒寫方式
$().ready() $().noConflict() 復制代碼要實現這樣,那么jQuery就要看成一個類,那么$()應該是返回類的實例才對 所以把代碼改一下:
var aQuery = function(selector, context) {returnnew aQuery(); } aQuery.prototype = {name:function(){},age:function(){} } 復制代碼通過new aQuery(),雖然返回的是一個實例,但是也能看出很明顯的問題,死循環了!
那么如何返回一個正確的實例?
在javascript中實例this只跟原型有關系 那么可以把jQuery類當作一個工廠方法來創建實例,把這個方法放到jQuery.prototye原型中
var aQuery = function(selector, context) {return aQuery.prototype.init(); } aQuery.prototype = {init:function(){returnthis;}name:function(){},age:function(){} } 復制代碼當執行aQuery() 返回的實例:
很明顯aQuery()返回的是aQuery類的實例,那么在init中的this其實也是指向的aQuery類的實例 問題來了init的this指向的是aQuery類,如果把init函數也當作一個構造器,那么內部的this要如何處理? var aQuery = function(selector, context) {return aQuery.prototype.init(); } aQuery.prototype = {init: function() {this.age = 18returnthis;},name: function() {},age: 20 }aQuery().age //18 復制代碼這樣的情況下就出錯了,因為this只是指向aQuery類的,所以需要設計出獨立的作用域才行
jQuery框架分隔作用域的處理
jQuery = function( selector, context ) {// The jQuery object is actually just the init constructor 'enhanced'returnnew jQuery.fn.init( selector, context, rootjQuery );}, 復制代碼很明顯通過實例init函數,每次都構建新的init實例對象,來分隔this,避免交互混淆 那么既然都不是同一個對象那么肯定又出現一個新的問題 例如:
var aQuery = function(selector, context) {returnnew aQuery.prototype.init(); } aQuery.prototype = {init: function() {this.age = 18returnthis;},name: function() {},age: 20 }//Uncaught TypeError: Object [object Object] has no method 'name' console.log(aQuery().name()) 復制代碼拋出錯誤,無法找到這個方法,所以很明顯new的init跟jquery類的this分離了
怎么訪問jQuery類原型上的屬性與方法?
做到既能隔離作用域還能使用jQuery原型對象的作用域呢,還能在返回實例中訪問jQuery的原型對象? 實現的關鍵點
// Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; 復制代碼通過原型傳遞解決問題,把jQuery的原型傳遞給jQuery.prototype.init.prototype 換句話說jQuery的原型對象覆蓋了init構造器的原型對象 因為是引用傳遞所以不需要擔心這個循環引用的性能問題
var aQuery = function(selector, context) {returnnew aQuery.prototype.init(); } aQuery.prototype = {init: function() {returnthis;},name: function() {returnthis.age},age: 20 }aQuery.prototype.init.prototype = aQuery.prototype;console.log(aQuery().name()) //20 復制代碼百度借網友的一張圖,方便直接理解: fn解釋下,其實這個fn沒有什么特殊意思,只是jQuery.prototype的引用
分析二:鏈式調用
DOM鏈式調用的處理: 1.節約JS代碼. 2.所返回的都是同一個對象,可以提高代碼的效率
通過簡單擴展原型方法并通過return this的形式來實現跨瀏覽器的鏈式調用。 利用JS下的簡單工廠模式,來將所有對于同一個DOM對象的操作指定同一個實例。 這個原理就超簡單了
aQuery().init().name()分解 a = aQuery(); a.init() a.name() 復制代碼把代碼分解一下,很明顯實現鏈式的基本條件就是實例this的存在,并且是同一個
aQuery.prototype = {init: function() {returnthis;},name: function() {returnthis} } 復制代碼所以我們在需要鏈式的方法訪問this就可以了,因為返回當前實例的this,從而又可以訪問自己的原型了
aQuery.init().name() 復制代碼優點:節省代碼量,提高代碼的效率,代碼看起來更優雅 最糟糕的是所有對象的方法返回的都是對象本身,也就是說沒有返回值,這不一定在任何環境下都適合。
Javascript是無阻塞語言,所以他不是沒阻塞,而是不能阻塞,所以他需要通過事件來驅動,異步來完成一些本需要阻塞進程的操作,這樣處理只是同步鏈式,異步鏈式jquery從1.5開始就引入了Promise,jQuery.Deferred后期在討論。
分析三:插件接口
jQuery的主體框架就是這樣,但是根據一般設計者的習慣,如果要為jQuery或者jQuery prototype添加屬性方法,同樣如果要提供給開發者對方法的擴展,從封裝的角度講是不是應該提供一個接口才對,字面就能看懂是對函數擴展,而不是看上去直接修改prototype.友好的用戶接口,
jQuery支持自己擴展屬性,這個對外提供了一個接口,jQuery.fn.extend()來對對象增加方法 從jQuery的源碼中可以看到,jQuery.extend和jQuery.fn.extend其實是同指向同一方法的不同引用
jQuery.extend = jQuery.fn.extend = function() { jQuery.extend 對jQuery本身的屬性和方法進行了擴展
jQuery.fn.extend 對jQuery.fn的屬性和方法進行了擴展 通過extend()函數可以方便快速的擴展功能,不會破壞jQuery的原型結構
jQuery.extend = jQuery.fn.extend = function(){...}; 這個是連等,也就是2個指向同一個函數,怎么會實現不同的功能呢?這就是this 力量了!
針對fn與jQuery其實是2個不同的對象,在之前有講述: ● jQuery.extend 調用的時候,this是指向jQuery對象的(jQuery是函數,也是對象!),所以這里擴展在jQuery上。 ● 而jQuery.fn.extend 調用的時候,this指向fn對象,jQuery.fn 和jQuery.prototype指向同一對象,擴展fn就是擴展jQuery.prototype原型對象。 ● 這里增加的是原型方法,也就是對象方法了。所以jQuery的api中提供了以上2中擴展函數。 extend的實現
jQuery.extend = jQuery.fn.extend = function() {var src, copyIsArray, copy, name, options, clone,target = arguments[0] || {}, // 常見用法 jQuery.extend( obj1, obj2 ),此時,target為arguments[0]i = 1,length = arguments.length,deep = false;// Handle a deep copy situationif ( typeof target === "boolean" ) { // 如果第一個參數為true,即 jQuery.extend( true, obj1, obj2 ); 的情況deep = target; // 此時target是truetarget = arguments[1] || {}; // target改為 obj1// skip the boolean and the targeti = 2;}// Handle case when target is a string or something (possible in deep copy)if ( typeof target !== "object" && !jQuery.isFunction(target) ) { // 處理奇怪的情況,比如 jQuery.extend( 'hello' , {nick: 'casper})~~target = {};}// extend jQuery itself if only one argument is passedif ( length === i ) { // 處理這種情況 jQuery.extend(obj),或 jQuery.fn.extend( obj )target = this; // jQuery.extend時,this指的是jQuery;jQuery.fn.extend時,this指的是jQuery.fn--i;}for ( ; i < length; i++ ) {// Only deal with non-null/undefined valuesif ( (options = arguments[ i ]) != null ) { // 比如 jQuery.extend( obj1, obj2, obj3, ojb4 ),options則為 obj2、obj3...// Extend the base objectfor ( name in options ) {src = target[ name ];copy = options[ name ];// Prevent never-ending loopif ( target === copy ) { // 防止自引用,不贅述continue;}// Recurse if we're merging plain objects or arrays// 如果是深拷貝,且被拷貝的屬性值本身是個對象if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {if ( copyIsArray ) { // 被拷貝的屬性值是個數組copyIsArray = false;clone = src && jQuery.isArray(src) ? src : [];} else { 被拷貝的屬性值是個plainObject,比如{ nick: 'casper' }clone = src && jQuery.isPlainObject(src) ? src : {};}// Never move original objects, clone themtarget[ name ] = jQuery.extend( deep, clone, copy ); // 遞歸~// Don't bring in undefined values} elseif ( copy !== undefined ) { // 淺拷貝,且屬性值不為undefinedtarget[ name ] = copy;}}}}// Return the modified objectreturn target; 復制代碼總結:
● 通過new jQuery.fn.init() 構建一個新的對象,擁有init構造器的prototype原型對象的方法
● 通過改變prorotype指針的指向,讓這個新的對象也指向了jQuery類的原型prototype
● 所以這樣構建出來的對象就繼續了jQuery.fn原型定義的所有方法了
轉載于:https://juejin.im/post/5c0e6cd86fb9a049a570bd15
總結
以上是生活随笔為你收集整理的jQuery源码分析系列 : 整体架构的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C# 多线程之List的线程安全问题
- 下一篇: 各种推导式