jQuery源碼解讀之extend()與工具方法、執行個體方法詳解,jqueryextend

來源:互聯網
上載者:User

jQuery源碼解讀之extend()與工具方法、執行個體方法詳解,jqueryextend

本文執行個體講述了jQuery源碼解讀之extend()與工具方法、執行個體方法。分享給大家供大家參考,具體如下:

使用jQuery的時候會發現,jQuery中有的函數是這樣使用的:

$.get();$.post();$.getJSON();

有些函數是這樣使用的:

$('div').css();$('ul').find('li');

有些函數是這樣使用的:

$('li').each(callback);$.each(lis,callback);

這裡涉及到兩個概念:工具方法與執行個體方法。通常我們說的工具方法是指無需執行個體化就可以調用的函數,如第一段代碼;執行個體方法是必須執行個體化對象以後才可以調用的函數,如第二段代碼。jQuery中很多方法既是執行個體方法也是工具方法,只是調用方式略有不同,如第三段代碼。為了更清晰解釋Javascript中的工具方法與執行個體方法,進行如下測試。

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

通過以上測試可以得出結論,在原型中定義的是執行個體方法,在建構函式中直接添加的是工具方法;執行個體方法不能由建構函式調用,同理,工具方法也不能由執行個體調用。

當然執行個體方法不僅可以在原型中定義,有以下三種定義方法:

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

這三種方式的優先順序為:直接定義在執行個體上的變數的優先順序要高於定義在“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;};

(1)首先,jQuery和其原型中extend()方法的實現使用的同一個函數。

(2)當extend()中只有一個參數的時候,是為jQuery對象添加外掛程式。在jQuery上擴充的叫做工具方法,在jQuery.fn(jQuery原型)中擴充的是執行個體方法,即使在jQuery和原型上擴充相同名字的函數也可以,使用jQuery對象會調用工具方法,使用jQuery()會調用執行個體方法。

(3)當extend()中有多個參數時,後面的參數都擴充到第一個參數上。

var a={};$.extend(a,{name:"hello"},{age:10});console.log(a);//Object{name: "hello", age: 10}

(4)淺拷貝(預設):

var a={};varb={name:"hello"};$.extend(a,b);console.log(a);//Object{name: "hello"}a.name="hi";console.log(b);//Object{name: "hello"}

b不受a影響,但是如果b中一個屬性為對象:

var a={};varb={name:{age:10}};$.extend(a,b);console.log(a.name);//Object{age: 10}a.name.age=20;console.log(b.name);//Object{age: 20}

由於淺拷貝無法完成,則b.name會受到a的影響,這時我們往往希望深拷貝。

深拷貝:

var a={};varb={name:{age:10}};$.extend(true,a,b);console.log(a.name);//Object{age: 10}a.name.age=20;console.log(b.name);//Object{age: 10}

b.name不受a的影響。

var a={name:{job:"Web Develop"}};var b={name:{age:10}};$.extend(true,a,b);console.log(a.name);//age: 10 job: "Web Develop"//b.name沒有覆蓋a.name.job。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.