Analysis of the Jquery.extend () method

Source: Internet
Author: User

The Jquery.extend method is our common method and the basic method in the jquery source code. Its main function is to merge one or more "source objects" into one "target object" and return the target object. It has three main forms of expression:

A, Jquery.extend (destination, Source1, Source2, Source3 ...)

B, jquery.extend (source)

C, Jquery.extend (Boolean, Destination, Source1, Source2, Source3 ...)

A means the first parameter as the "target object", and the other parameter as the "source object".

The B method has only one parameter, and here the parameter becomes the "source object" and "target object" becomes jquery. To be blunt is the "source Object" property, which becomes a static method or property of the jquery function.

The first parameter of the C mode is a Boolean, the second argument is the target object, and the remaining argument is the source object. When the value of the first parameter is true, the "deep copy" is supported when an object is merged.

Knowing the use of the function, we must be curious about how jquery is implemented, and want to see the source of jquery. However, before looking at the jquery source code, we may as well try to write the function of this method, and then look back to the jquery source code, the feeling may be deeper, see the more things possible.

Let's not give ourselves pressure first, from the simplest start, to achieve the method of two parameters: the first parameter is: "Target Object", the second argument is: "Source object." The first implementation merges the source object into the target object. The code is as follows:

var function  function(destination, source) {    for(var in source) {         = Source[key]    }    return  Destination}

The second implementation can pass in multiple parameters, the first parameter is the target object, and the other parameter is the source object. The code is as follows:

 test.extend1 = function   () { var  Destination = Arguments[0 var  Sourcearr = Array.prototype.slice.call (Arguments,1 for  (var  i = 0, len = sourcearr.length; i < Len; I++ var  source = Sourcearr[i] for  (var  Key in   source) {Destination[key]  = Source[key]}}  return   destination}  

The third step is to append the properties of the Parameter object to test when only one parameter is implemented. The code is as follows:

Test.extend2 =function(){    varArgumentslen =Arguments.lengthif(Argumentslen = = 1 ){        varSource = Arguments[0]         for(varKeyinchsource) {Test[key]=Source[key]}}Else{        varDestination = Arguments[0]        varSourcearr = Array.prototype.slice.call (arguments,1)         for(vari = 0, len = sourcearr.length; i < Len; i++){            varSource =Sourcearr[i] for(varKeyinchsource) {Destination[key]=Source[key]}} returnDestination}}

The fourth step realizes "deep copy", the first parameter is whether to make a deep copy of the Boolean judgment, the second parameter is the target object, the other parameters are the source object. The code is as follows:

Test.extend3 =function(){    varArgumentslen =Arguments.lengthif(Argumentslen = = 1 ){        varSource = Arguments[0]         for(varKeyinchsource) {Test[key]=Source[key]}}Else{        varFirstItem = Arguments[0]        varIsboolean =typeofFirstItem = = = "Boolean"varDestination = Isboolean? Arguments[1]: FirstItemvarStartnum = Isboolean? 2:1varSourcearr =Array.prototype.slice.call (arguments,startnum) for(vari = 0, len = sourcearr.length; i < Len; i++){            varSource =Sourcearr[i]if(Isboolean) {deepextend (destination, source)}Else{                 for(varKeyinchsource) {Destination[key]=Source[key]}} }        returnDestination}}functiondeepextend (destination, source) { for(varKeyinchsource) {        varValue =Source[key]if(ValueinstanceofArray) {Destination[key]= Arguments.callee.call (Destination[key] | |[], value)}Else if(ValueinstanceofObject) {Destination[key]= Arguments.callee.call (Destination[key] | |{}, value)}Else{Destination[key]=Source[key]}} returnDestination}

Well, we follow our own ideas, rough implementation of their own extend method, now look at the implementation of jquery on extend, comparative study. The source code is as follows:

Jquery.extend = JQuery.fn.extend =function() {    varsrc, copyisarray, copy, name, options, clone, Target= Arguments[0] | |{}, I= 1, Length=Arguments.length, deep=false; //Handle a deep copy situation    if(typeoftarget = = = "Boolean") { deep=Target; //Skip the Boolean and the targettarget = arguments[I] | | {}; I++; }    //Handle Case If Target is a string or something (possible in deep copy)    if(typeofTarget!== "Object" &&!jquery.isfunction (target)) {Target= {}; }    //extend JQuery 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(Nameinchoptions) {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 themtarget[name] =jquery.extend (deep, clone, copy); //Don ' t bring in undefined values}Else if(Copy!==undefined) {target[name]=copy; }            }        }    }    //Return the Modified object    returnTarget;}

By contrast, we found that:

A, jquery is more elegant in code organization and implementation.

B, jquery takes into account some special circumstances. Like what:

if (target = = copy)      {continue;}

This is to avoid infinite loops, where the property of the source object points to the target object, and when the object is merged, it copies itself to its own properties. This is not advisable.

C, jQuery in the array (Jquery.isarray) and "Pure Object" (Jquery.isplainobject) judgment, consider more fine.

First of all think about their own ideas to achieve, and then in contrast to study, this learning method feels very good. A, strengthen the ability of independent thinking. B, discover new learning content. C, the leakage of their own shortcomings.

Analysis of the Jquery.extend () method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.