本文實(shí)例講述了jQuery源碼解讀之extend()與工具方法、實(shí)例方法。分享給大家供大家參考,具體如下:
使用jQuery的時(shí)候會發(fā)現(xiàn),jQuery中有的函數(shù)是這樣使用的:
$.get();$.post();$.getJSON();
有些函數(shù)是這樣使用的:
$('div').css();$('ul').find('li');有些函數(shù)是這樣使用的:
$('li').each(callback);$.each(lis,callback);這里涉及到兩個(gè)概念:工具方法與實(shí)例方法。通常我們說的工具方法是指無需實(shí)例化就可以調(diào)用的函數(shù),如第一段代碼;實(shí)例方法是必須實(shí)例化對象以后才可以調(diào)用的函數(shù),如第二段代碼。jQuery中很多方法既是實(shí)例方法也是工具方法,只是調(diào)用方式略有不同,如第三段代碼。為了更清晰解釋JavaScript中的工具方法與實(shí)例方法,進(jìn)行如下測試。
function A(){}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 functionA.fun_c();//constructora.fun_p();//prototpyea.fun_c();//a.fun_c is not a function通過以上測試可以得出結(jié)論,在原型中定義的是實(shí)例方法,在構(gòu)造函數(shù)中直接添加的是工具方法;實(shí)例方法不能由構(gòu)造函數(shù)調(diào)用,同理,工具方法也不能由實(shí)例調(diào)用。
當(dāng)然實(shí)例方法不僅可以在原型中定義,有以下三種定義方法:
function A(){ this.fun_f=function(){ console.log("Iam in the constructor"); };}A.prototype.fun_p=function(){ console.log("Iam in the prototype");};var a=new A();a.fun_f();//Iam in the constructora.fun_i=function(){ console.log("Iam in the instance");};a.fun_i();//Iam in the instancea.fun_p();//Iam in the prototype這三種方式的優(yōu)先級為:直接定義在實(shí)例上的變量的優(yōu)先級要高于定義在“this”上的,而定義在“this”上的又高于 prototype定義的變量。即直接定義在實(shí)例上的變量會覆蓋定義在“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;};
新聞熱點(diǎn)
疑難解答
圖片精選