DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> jQuery入門知識 >> JQuery特效代碼 >> jQuery源碼分析-03構造jQuery對象-工具函數
jQuery源碼分析-03構造jQuery對象-工具函數
編輯:JQuery特效代碼     
作者:nuysoft/高雲 QQ:47214707 EMail:[email protected]
聲明:本文為原創文章,如需轉載,請注明來源並保留原文鏈接。
讀讀寫寫,不對的地方請告訴我,多多交流共同進步,本章的的PDF等本章寫完了發布。
jQuery源碼分析系列的目錄請查看 http://nuysoft.iteye.com/blog/1177451,想系統的好好寫寫,目前還是從我感興趣的部分開始,如果大家有對哪個模塊感興趣的,建議優先分析的,可以告訴我,一起學習。
3.4 其他靜態工具函數
. 代碼如下:
// 擴展工具函數
jQuery.extend({
// 釋放$的 jQuery 控制權
// 許多 JavaScript 庫使用 $ 作為函數或變量名,jQuery 也一樣。
// 在 jQuery 中,$ 僅僅是 jQuery 的別名,因此即使不使用 $ 也能保證所有功能性。
// 假如我們需要使用 jQuery 之外的另一 JavaScript 庫,我們可以通過調用 $.noConflict() 向該庫返回控制權。
// 通過向該方法傳遞參數 true,我們可以將 $ 和 jQuery 的控制權都交還給另一JavaScript庫。
noConflict: function( deep ) {
// 交出$的控制權
if ( window.$ === jQuery ) {
window.$ = _$;
}
// 交出jQuery的控制權
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
// 一個計數器,用於跟蹤在ready事件出發前的等待次數
readyWait: 1,
// Hold (or release) the ready event
// 繼續等待或觸發
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
// 文檔加載完畢句柄
ready: function( wait ) {
// Either a released hold or an DOMready/load event and not yet ready
//
if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
// 確保document.body存在
if ( !document.body ) {
return setTimeout( jQuery.ready, 1 );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger( "ready" ).unbind( "ready" );
}
}
},
// 初始化readyList事件處理函數隊列
// 兼容不同浏覽對綁定事件的區別
bindReady: function() {
if ( readyList ) {
return;
}
readyList = jQuery._Deferred();
// Catch cases where $(document).ready() is called after the
// browser event has already occurred.
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
return setTimeout( jQuery.ready, 1 );
}
// Mozilla, Opera and webkit nightlies currently support this event
// 兼容事件,通過檢測浏覽器的功能特性,而非嗅探浏覽器
if ( document.addEventListener ) {
// Use the handy event callback
// 使用較快的加載完畢事件
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
// 注冊window.onload回調函數
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
// 確保在onload之前觸發onreadystatechange,可能慢一些但是對iframes更安全
document.attachEvent( "onreadystatechange", DOMContentLoaded );
// A fallback to window.onload, that will always work
// 注冊window.onload回調函數
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var toplevel = false;
try {
toplevel = window.frameElement == null;
} catch(e) {}
if ( document.documentElement.doScroll && toplevel ) {
doScrollCheck();
}
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
// 是否函數
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
// 是否數組
// 如果浏覽器有內置的 Array.isArray 實現,就使用浏覽器自身的實現方式,
// 否則將對象轉為String,看是否為"[object Array]"。
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
// A crude way of determining if an object is a window
// 簡單的判斷(判斷setInterval屬性)是否window對象
isWindow: function( obj ) {
return obj && typeof obj === "object" && "setInterval" in obj;
},
// 是否是保留字NaN
isNaN: function( obj ) {
// 等於null 或 不是數字 或調用window.isNaN判斷
return obj == null || !rdigit.test( obj ) || isNaN( obj );
},
// 獲取對象的類型
type: function( obj ) {
// 通過核心API創建一個對象,不需要new關鍵字
// 普通函數不行
// 調用Object.prototype.toString方法,生成 "[object Xxx]"格式的字符串
// class2type[ "[object " + name + "]" ] = name.toLowerCase();
return obj == null ?
String( obj ) :
class2type[ toString.call(obj) ] || "object";
},
// 檢查obj是否是一個純粹的對象(通過"{}" 或 "new Object"創建的對象)
// console.info( $.isPlainObject( {} ) ); // true
// console.info( $.isPlainObject( '' ) ); // false
// console.info( $.isPlainObject( document.location ) ); // true
// console.info( $.isPlainObject( document ) ); // false
// console.info( $.isPlainObject( new Date() ) ); // false
// console.info( $.isPlainObject( ) ); // false
// isPlainObject分析與重構 http://www.jb51.net/article/25047.htm
// 對jQuery.isPlainObject()的理解 http://www.cnblogs.com/phpmix/articles/1733599.html
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
// 必須是一個對象
// 因為在IE8中會拋出非法指針異常,必須檢查constructor屬性
// DOM節點和window對象,返回false
// obj不存在 或 非object類型 或 DOM節點 或 widnow對象,直接返回false
// 測試以下三中可能的情況:
// jQuery.type(obj) !== "object" 類型不是object,忽略
// obj.nodeType 認為DOM節點不是純對象
// jQuery.isWindow( obj ) 認為window不是純對象
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
// Not own constructor property must be Object
// 測試constructor屬性
// 具有構造函數constructor,卻不是自身的屬性(即通過prototype繼承的),
if ( obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
// key === undefined及不存在任何屬性,認為是簡單的純對象
// hasOwn.call( obj, key ) 屬性key不為空,且屬性key的對象自身的(即不是通過prototype繼承的)
return key === undefined || hasOwn.call( obj, key );
},
// 是否空對象
isEmptyObject: function( obj ) {
for ( var name in obj ) {
return false;
}
return true;
},
// 拋出一個異常
error: function( msg ) {
throw msg;
},
// 解析JSON
// parseJSON把一個字符串變成JSON對象。
// 我們一般使用的是eval。parseJSON封裝了這個操作,但是eval被當作了最後手段。
// 因為最新JavaScript標准中加入了JSON序列化和反序列化的API。
// 如果浏覽器支持這個標准,則這兩個API是在JS引擎中用Native Code實現的,效率肯定比eval高很多。
// 目前來看,Chrome和Firefox4都支持這個API。
parseJSON: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Attempt to parse using the native JSON parser first
// 原生JSON API。反序列化是JSON.stringify(object)
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
// ... 大致地檢查一下字符串合法性
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return (new Function( "return " + data ))();
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
// (xml & tmp used internally)
// 解析XML 跨浏覽器
// parseXML函數也主要是標准API和IE的封裝。
// 標准API是DOMParser對象。
// 而IE使用的是Microsoft.XMLDOM的 ActiveXObject對象。
parseXML: function( data , xml , tmp ) {
if ( window.DOMParser ) { // Standard 標准XML解析器
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE IE的XML解析器
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
tmp = xml.documentElement;
if ( ! tmp || ! tmp.nodeName || tmp.nodeName === "parsererror" ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
// 無操作函數
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
// globalEval函數把一段腳本加載到全局context(window)中。
// IE中可以使用window.execScript。
// 其他浏覽器 需要使用eval。
// 因為整個jQuery代碼都是一整個匿名函數,所以當前context是jQuery,如果要將上下文設置為window則需使用globalEval。
globalEval: function( data ) {
// data非空
if ( data && rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// 判斷節點名稱是否相同
nodeName: function( elem, name ) {
// 忽略大小寫
return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
},
// args is for internal usage only
// 遍歷對象或數組
each: function( object, callback, args ) {
var name, i = 0,
length = object.length,
isObj = length === undefined || jQuery.isFunction( object );
// 如果有參數args,調用apply,上下文設置為當前遍歷到的對象,參數使用args
if ( args ) {
if ( isObj ) {
for ( name in object ) {
if ( callback.apply( object[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( object[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
// 沒有參數args則調用,則調用call,上下文設置為當前遍歷到的對象,參數設置為key/index和value
} else {
if ( isObj ) {
for ( name in object ) {
if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) {
break;
}
}
}
}
return object;
},
// Use native String.trim function wherever possible
// 盡可能的使用本地String.trim方法,否則先過濾開頭的空格,再過濾結尾的空格
trim: trim ?
function( text ) {
return text == null ?
"" :
trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
},
// results is for internal usage only
// 將偽數組轉換為數組
makeArray: function( array, results ) {
var ret = results || [];
if ( array != null ) {
// The window, strings (and functions) also have 'length'
// The extra typeof function check is to prevent crashes
// in Safari 2 (See: #3039)
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
// 一大堆浏覽器兼容性測試,真實蛋疼
var type = jQuery.type( array );
// 測試:有沒有length屬性、字符串、函數、正則
// 不是數組,連偽數組都不是
if ( array.length == null
|| type === "string"
|| type === "function"
|| type === "regexp"
|| jQuery.isWindow( array ) ) {
push.call( ret, array );
} else {
// $.type( $('div') ) // object
jQuery.merge( ret, array );
}
}
return ret;
},
//
inArray: function( elem, array ) {
// 是否有本地化的Array.prototype.indexOf
if ( indexOf ) {
// 直接調用Array.prototype.indexOf
return indexOf.call( array, elem );
}
// 遍歷數組,查找是否有完全相等的元素,並返回下標
// 循環的小技巧:把array.length存放到length變量中,可以減少一次作用域查找
for ( var i = 0, length = array.length; i < length; i++ ) {
if ( array[ i ] === elem ) {
return i;
}
}
// 如果返回-1,則表示不在數組中
return -1;
},
// 將數組second合並到數組first中
merge: function( first, second ) {
var i = first.length, //
j = 0;
// 如果second的length屬性是Number類型,則把second當數組處理
if ( typeof second.length === "number" ) {
for ( var l = second.length; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
// 遍歷second,將非undefined的值添加到first中
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
// 修正first的length屬性,因為first可能不是真正的數組
first.length = i;
return first;
},
// 過濾數組,返回新數組;callback返回true時保留;如果inv為true,callback返回false才會保留
grep: function( elems, callback, inv ) {
var ret = [], retVal;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
// 遍歷數組,只保留通過驗證函數callback的元素
for ( var i = 0, length = elems.length; i < length; i++ ) {
// 這裡callback的參數列表為:value, index,與each的習慣一致
retVal = !!callback( elems[ i ], i );
// 是否反向選擇
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
// 將數組或對象elems的元素/屬性,轉化成新的數組
map: function( elems, callback, arg ) {
var value, key, ret = [],
i = 0,
length = elems.length,
// jquery objects are treated as arrays
// 檢測elems是否是(偽)數組
// 1. 將jQuery對象也當成數組處理
// 2. 檢測length屬性是否存在,length等於0,或第一個和最後一個元素是否存在,或jQuery.isArray返回true
isArray = elems instanceof jQuery
|| length !== undefined && typeof length === "number"
&& ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
// 是數組或對象的差別,僅僅是遍歷的方式不同,沒有其他的區別
// Go through the array, translating each of the items to their
// 遍歷數組,對每一個元素調用callback,將返回值不為null的值,存入ret
if ( isArray ) {
for ( ; i < length; i++ ) {
// 執行callback,參數依次為value, index, arg
value = callback( elems[ i ], i, arg );
// 如果返回null,則忽略(無返回值的function會返回undefined)
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
// 遍歷對象,對每一個屬性調用callback,將返回值不為null的值,存入ret
} else {
for ( key in elems ) {
// 執行callback,參數依次為value, key, arg
value = callback( elems[ key ], key, arg );
// 同上
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
// 使嵌套數組變平
// concat:
// 如果某一項為數組,那麼添加其內容到末尾。
// 如果該項目不是數組,就將其作為單個的數組元素添加到數組的末尾。
return ret.concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
// 代理方法:為fn指定上下文(即this)
// jQuery.proxy( function, context )
// jQuery.proxy( context, name )
proxy: function( fn, context ) {
// 如果context是字符串,設置上下文為fn,fn為fn[ context ]
// 即設置fn的context方法的上下文為fn(默認不是這樣嗎???TODO)
if ( typeof context === "string" ) {
var tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
// 快速測試fn是否是可調用的(即函數),在文檔說明中,會拋出一個TypeError,
// 但是這裡僅返回undefined
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
var args = slice.call( arguments, 2 ), // 從參數列表中去掉fn,context
proxy = function() {
// 設置上下文為context和參數
return fn.apply( context, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
// 統一guid,使得proxy能夠被移除
proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
return proxy;
},
// Mutifunctional method to get and set values to a collection
// The value/s can be optionally by executed if its a function
// 多功能函數,讀取或設置集合的屬性值;值為函數時會被執行
// fn:jQuery.fn.css, jQuery.fn.attr, jQuery.fn.prop
access: function( elems, key, value, exec, fn, pass ) {
var length = elems.length;
// Setting many attributes
// 如果有多個屬性,則迭代
if ( typeof key === "object" ) {
for ( var k in key ) {
jQuery.access( elems, k, key[k], exec, fn, value );
}
return elems;
}
// Setting one attribute
// 只設置一個屬性
if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = !pass && exec && jQuery.isFunction(value);
for ( var i = 0; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
return elems;
}
// Getting an attribute
// 讀取屬性
return length ? fn( elems[0], key ) : undefined;
},
// 獲取當前時間的便捷函數
now: function() {
return (new Date()).getTime();
},
// Use of jQuery.browser is frowned upon.
// More details: http://docs.jquery.com/Utilities/jQuery.browser
// 不贊成使用jQuery.browser,推薦使用jQuery.support
// Navigator 正在使用的浏覽器的信息
// Navigator.userAgent 一個只讀的字符串,聲明了浏覽器用於HTPP請求的用戶代理頭的值
uaMatch: function( ua ) {
ua = ua.toLowerCase();
// 依次匹配各浏覽器
var match = rwebkit.exec( ua ) ||
ropera.exec( ua ) ||
rmsie.exec( ua ) ||
ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
[];
// match[1] || ""
// match[1]為false(空字符串、null、undefined、0等)時,默認為""
// match[2] || "0"
// match[2]為false(空字符串、null、undefined、0等)時,默認為"0"
return { browser: match[1] || "", version: match[2] || "0" };
},
// 創建一個新的jQuery副本,副本的屬性和方法可以被改變,但是不會影響原始的jQuery對象
// 有兩種用法:
// 1. 覆蓋jQuery的方法,而不破壞原始的方法
// 2.封裝,避免命名空間沖突,可以用來開發jQuery插件
// 值得注意的是,jQuery.sub()函數並不提供真正的隔離,所有的屬性、方法依然指向原始的jQuery
// 如果使用這個方法來開發插件,建議優先考慮jQuery UI widget工程
sub: function() {
function jQuerySub( selector, context ) {
return new jQuerySub.fn.init( selector, context );
}
jQuery.extend( true, jQuerySub, this ); // 深度拷貝,將jQuery的所有屬性和方法拷貝到jQuerySub
jQuerySub.superclass = this;
jQuerySub.fn = jQuerySub.prototype = this(); //
jQuerySub.fn.constructor = jQuerySub;
jQuerySub.sub = this.sub;
jQuerySub.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
context = jQuerySub( context );
}
return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
};
jQuerySub.fn.init.prototype = jQuerySub.fn;
var rootjQuerySub = jQuerySub(document);
return jQuerySub;
},
// 浏覽器類型和版本:
// $.browser.msie/mozilla/webkit/opera
// $.browser.version
// 不推薦嗅探浏覽器類型jQuery.browser,而是檢查浏覽器的功能特性jQuery.support
// 未來jQuery.browser可能會移到一個插件中
browser: {}
});
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved