jQuery extend()詳解及簡單實例
使用jQuery的時候會發現,jQuery中有的函數是這樣使用的:
$.get(); $.post(); $.getJSON();
有些函數是這樣使用的:
$('div').css(); $('ul').find('li'); 有些函數是這樣使用的:
$('li').each(callback); $.each(lis,callback); 這里涉及到兩個概念:工具方法與實例方法。通常我們說的工具方法是指無需實例化就可以調用的函數,如第一段代碼;實例方法是必須實例化對象以后才可以調用的函數,如第二段代碼。jQuery中很多方法既是實例方法也是工具方法,只是調用方式略有不同,如第三段代碼。為了更清晰解釋JavaScript中的工具方法與實例方法,進行如下測試。
functionA(){ } A.prototype.fun_p=function(){console.log("prototpye");}; A.fun_c=function(){console.log("constructor");}; var a=new A(); A.fun_p();//A.fun_p is not a function A.fun_c();//constructor a.fun_p();//prototpye a.fun_c();//a.fun_c is not a function 通過以上測試可以得出結論,在原型中定義的是實例方法,在構造函數中直接添加的是工具方法;實例方法不能由構造函數調用,同理,工具方法也不能由實例調用。
當然實例方法不僅可以在原型中定義,有以下三種定義方法:
functionA(){ this.fun_f=function(){ console.log("Iam in the constructor"); }; } A.prototype.fun_p=function(){ console.log("Iam in the prototype"); }; var a=newA(); a.fun_f();//Iam in the constructor a.fun_i=function(){ console.log("Iam in the instance"); }; a.fun_i();//Iam in the instance a.fun_p();//Iam in the prototype 這三種方式的優先級為:直接定義在實例上的變量的優先級要高于定義在“this”上的,而定義在“this”上的又高于 prototype定義的變量。即直接定義在實例上的變量會覆蓋定義在“this”上和prototype定義的變量,定義在“this”上的會覆蓋prototype定義的變量。
下面看jQuery中extend()方法源碼:
jQuery.extend = jQuery.fn.extend = function() { var options,name, src, copy, copyIsArray, clone, target= arguments[0] || {}, i =1, length= arguments.length, deep= false; // Handle adeep copy situation if ( typeoftarget === "boolean" ) { deep= target; //Skip the boolean and the target target= arguments[ i ] || {}; i++; } // Handlecase when target is a string or something (possible in deep copy) if ( typeoftarget !== "object" && !jQuery.isFunction(target) ) { target= {}; } // ExtendjQuery itself if only one argument is passed if ( i ===length ) { target= this; i--; } for ( ; i< length; i++ ) { //Only deal with non-null/undefined values if ((options = arguments[ i ]) != null ) { //Extend the base object for( name in options ) { src= target[ name ]; copy= options[ name ]; //Prevent never-ending loop if( target === copy ) { continue; } //Recurse if we're merging plain objects or arrays if( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray= jQuery.isArray(copy)) ) ) { if( copyIsArray ) { copyIsArray= false; clone= src && jQuery.isArray(src) ? src : []; }else { clone= src && jQuery.isPlainObject(src) ? src : {}; } //Never move original objects, clone them target[name ] = jQuery.extend( deep, clone, copy ); //Don't bring in undefined values }else if ( copy !== undefined ) { target[name ] = copy; } } } } // Returnthe modified object return target; };
新聞熱點
疑難解答
圖片精選