1.2.7.2.深入瞭解原始碼:jQeury(二)
Jquery 裡的另一個eningee: 給他一個字串他會找到HTML
所以傳入selector的字串, 可以用sizzle做到
jQuery的函數建構子
呼叫new運算子會建立新的空物件, 如果不自己回傳值, 他會自己回傳
如果把一個函數當成建構子, this將會指向被new運算子建立的空物件
參考jQuery的函數建構子的作法, 可以將this變數傳入另一個函數做處理, 接著從函數建構子回傳
init = jQuery.fn.init = function( selector, context, root ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // init accepts an alternate rootjQuery // so migrate can support jQuery.sub (gh-2101) root = root || rootjQuery; ... // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return typeof root.ready !== "undefined" ? root.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn;
建立一個jQuery物件時, 實際上jQuery做了甚麼事
1.呼叫函數用new關鍵子呼叫函數建構子接著建立新物件
jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }, init = jQuery.fn.init = function( selector, context, root ) { ... }
2.新物件可以取用這裡所有的屬性與方法
將新物件的原型指向函數的.prototype屬性
// Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn;
Last updated
Was this helpful?