jQuery源码解析2(Core)
我们知道 $('#id') 或 jQuery('#id') 将会返回一个对象, 这个对象的构造函数是:jQuery.fn.init
- jQuery = window.jQuery = window.$ = function( selector, context ) {
- return new jQuery.fn.init( selector, context );
- },
jQuery = window.jQuery = window.$ = function( selector, context ) {
return new jQuery.fn.init( selector, context );
},
- jQuery.fn.init.prototype = jQuery.fn;
jQuery.fn.init.prototype = jQuery.fn;
让我们先看看 jQuery.fn.init
- jQuery.fn = jQuery.prototype = {
- init: function( selector, context ) {
- selector = selector || document;
jQuery.fn = jQuery.prototype = {
init: function( selector, context ) {
selector = selector || document;
selector 可以指定不同的数据类型,我们一个一个来:
1. jQuery(element); // an html dom element
- // Handle $(DOMElement)
- if ( selector.nodeType ) {
- this[0] = selector;
- this.length = 1;
- this.context = selector;
- return this;
- }
// Handle $(DOMElement)
if ( selector.nodeType ) {
this[0] = selector;
this.length = 1;
this.context = selector;
return this;
}
所以我们可以这样使用:
var elem = $(element); // 用于包装一个html dom元素, 以便使用jQuery操作它。
注意到以上代码,所以我们还可以像数组一样使用它:)
elem[0];// return html dom element
elem.length;//
2. jQuery(html, [context]), jQuery(elements, [context])
- if ( typeof selector === "string" ) {
- // Are we dealing with HTML string or an ID?
- var match = quickExpr.exec( selector );
- // Verify a match, and that no context was specified for #id
- if ( match && (match[1] || !context) ) {
- // HANDLE: $(html) -> $(array)
- if ( match[1] )
- selector = jQuery.clean( [ match[1] ], context );
if ( typeof selector === "string" ) {
// Are we dealing with HTML string or an ID?
var match = quickExpr.exec( selector );
// Verify a match, and that no context was specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] )
selector = jQuery.clean( [ match[1] ], context );
quickExpr 是一个正则式,用于匹配一个html string 或 id 字符串 (见第1篇)
