原文連接在這裏,做爲一個菜鳥,我就一邊讀一邊寫javascript
前面看着差很少了,看到下面一條(我是真菜鳥),推薦木有入門或者剛剛JS入門摸不着邊的看看,大大們手下留情,想一塊兒學習JS的能夠給我留言。java
// Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn;
看到這裏的時候有點迷茫啊。這個fn是啥玩意,百思不得其姐。最後只能找度娘了jquery
jQuery.fn = jQuery.prototype = { init: function( selector, context ) {//…. //…… };
而後發現,fn就是prototype 文章來源 jquery.fn.extend與jquery.extend數組
上面的意思其實就是oop
jQuery.prototype.init.prototype = jQuery.prototype;
往下走源碼分析
aQuery.prototype = { init: function() { return this; }, name: function() { return this } }
明顯實現鏈式的基本條件就是實例this的存在,而且是同一個學習
換句話說,就是被jQuery的方法處理以後,返回的對象仍是處理以前的對象(初學者這麼理解會好理解一些)。this
extend的實現,我就只把英文翻譯成中文- -,這個能看懂就能看懂,我明天整理了,再後面寫下分析,其實說的已經很詳細了。。spa
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 situation //處理深拷貝狀況 if ( typeof target === "boolean" ) { // 若是第一個參數爲true,即 jQuery.extend( true, obj1, obj2 ); 的狀況 deep = target; // 此時target是true target = arguments[1] || {}; // target改成 obj1 // skip the boolean and the target i = 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 passed //繼承jQuery對象本身,若是它只有一個參數傳遞 if ( 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 values //只處理值 non-null/undefined if ( (options = arguments[ i ]) != null ) { // 好比 jQuery.extend( obj1, obj2, obj3, ojb4 ),options則爲 obj二、obj3... // Extend the base object //繼承基礎對象 for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop //防止無休止的循環 if ( 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 them //不移動原對象,克隆他們 target[ name ] = jQuery.extend( deep, clone, copy ); // 遞歸~ // Don't bring in undefined values //不傳undefined值 } else if ( copy !== undefined ) { // 淺拷貝,且屬性值不爲undefined target[ name ] = copy; } } } } // Return the modified object //返回修改後的對象 return target;
下一次有空再看一遍以防忘記。
@北川 老師勿噴
歡迎各位留言互相學習。
恩,能看懂多少看多少把,還有一些,在後面的文章裏面會看到。到時候有相關的內容,回頭再看這個。收益會更大