jQuery擴充寫法(jQuery extend)

jquery的擴充方式有兩種,一種是靜態的擴充,另一個則是prototype擴充,靜態擴充只是將function、object….等,添加在jquery底下,與沒添加前功能相同,但是prototype則不同,prototype擴充可以將你所抓取的element做處理,以下是一個很典型的做法。

example:
(function($){
    //prototype extend
    $.fn.extend({
        drawRed:function(){
            //
            return this.each(function(){

                //$(this).css("background-color","red");
                this.style.backgroundColor = "red";
            });

        }
    });
    //static extend
    $.extend({
        draw:function(){
            console.log("draw");
        }
    });
})(jQuery);
//
$("div").drawRed();
$.draw();

其中each是一個非常重要的東西,因為使用jquery抓取的element會create一個Array,而這個Array與一般的Array的prototype是分開的,只是擁有相同的prototype attribute,當呼叫到each時,他會將array裡所有存放的資料,都執行過一邊,each傳入的function中,使用this是指向array裡執行到的element,所以若是沒有使用eachjquery所抓取的數個elements,呼叫到drawRed只會執行一次,而且this指向的是Array本身。

jqueryextend傳入參數只有一個物件時,則是擴充jquery本身,若是對jquery的實作方式有興趣,請參考jQuery.fn.initjQuery.fn.extend這兩個function