觀看者:javascript,jquery愛好者。需要一定的繼承基礎,如果沒有可以看我的javascript深入瞭解(繼承)
目標:瞭解jquery原型繼承,實現jquery選取器的基礎 $("id"),$("input") ...
實現方式:代碼及相關文字解釋。從最簡單方式逐步推進。首先用一個實現一個簡單的實現:$("id") 返回一個jquery對象有一個方法tagName();於是我想到這樣的:
$ = window.JQuery = function(id){return new JQuery(id);}
寫到這裡我實在寫不下去了應為我想返回一個jquery對象,但是當我new調用的自身的建構函式,直接死迴圈。
那麼我們可不可以new出一個另外的對象返回呢?
$ = window.JQuery = function(id){return new JQuerylite(id);}JQuerylite = function(id){this.dom = document.getElementById("dv");this.tagName = function(){alert(this.dom.tagName);}}$("dv").tagName();
這樣是可以實現的,但是不夠完美,通過了兩個無關的建構函式,實在浪費。我們可以換種思路,我們可以將JQuerylite修改成一個jquery的內建函式,
我們知道其實函數也是構造方法,這樣一來我們的對象不僅指的是juqery對象,同時我們還有jquery原生的方法。一舉兩得下面是我們修改後的例子。
$ = window.JQuery = function(id){return new JQuery.prototype.init(id);}JQuery.prototype = {init:function(id){this.dom = document.getElementById("dv");this.tagName = function(){alert(this.dom.tagName.toLowerCase());};this.version = '1.71';},version:'1.7',name:'JQuery'}alert($("dv").version);//1.71alert($("dv").name);//undefined$("dv").tagName();//div
alert($("dv").name);//undefined,這個課不是我們想要的,我們需要的是JQuery裡面的name值,為什麼沒有呢?
我前面的javascript深入瞭解(物件導向)裡面也講過,這裡我再回顧一遍吧,當我們new 出來的JQuery.prototype.init(id),其實是調用的是JQuery.prototype.init的構造方法,如此一來我們共用的原型應該是JQuery.prototype.init.prototype = {},所以我們這裡調用不到了,不過還有個方法是想法子將JQuery的prototype賦值給JQuery.prototype.init.prototype就行了。下面看例子:
$ = window.JQuery = function(id){return new JQuery.prototype.init(id);}JQuery.prototype = {init:function(id){this.dom = document.getElementById("dv");this.tagName = function(){alert(this.dom.tagName.toLowerCase());};this.version = '1.71';},version:'1.7',name:'JQuery'}JQuery.prototype.init.prototype = JQuery.prototype;alert($("dv").version);//1.71alert($("dv").name);//undefined$("dv").tagName();//div
到此我們已經把基本的構造得到了,下一步我們來寫個選取器的簡單例子,用來練習一下吧:
實現以$(selector,context).size() 得到dom個數,selector 可以是id或者是標籤名,context 是範圍。
(function(){$ = window.JQuery = function(selector,context){return new JQuery.prototype.init(selector,context);}JQuery.prototype = {init:function(selector,context){var selector = selector ? selector : document;var context = context ? context : document;var dom;if(dom = context.getElementById(selector)){this[0] = dom;this.length = 1;}else{dom = context.getElementsByTagName(selector);for(var i=0; i<dom.length; i++){this[i] = dom[i];}this.length = dom.length;}},version:'1.7',size:function(){return this.length;}}JQuery.prototype.init.prototype = JQuery.prototype;})();alert($("div").size());//3alert($("dv").size());//1
就是想講一下jquery一個機制,jquery的選取器當然比這個要強大的更多。為什麼要用私人範圍((function(){})();)包起來呢?其實是為了怕會影響其他的外部函數和變數。想瞭解匿名函數的原理還需要看我原來寫的文章javascript深入瞭解(私人範圍)。