Jquery.extend is one of the most important ways of jquery, so let's look at how jquery can be implemented to extend operations
1 //If an object is passed in, the object's properties are added to the jquery object2 3 //if two or more objects are passed in, the properties of all objects are added to the first object4 5 //If you want to merge two objects, you can use this: $.extend ({}, obj1, obj2);6 7 //If the first argument is true, a deep copy is performed (iterative merge)8 9 Ten OneJquery.extend = JQuery.fn.extend =function() { A varsrc, copyisarray, copy, name, options, clone, -target = Arguments[0] | | {},//gets the first argument, the 1th parameter chooses whether to make a deep copy -i = 1, theLength =Arguments.length, -Deep =false; - - //working with deep copies + if(typeoftarget = = = "Boolean" ) { -Deep =Target; + //skips the first Boolean value Atarget = arguments[I] | | {};//i = = 1 ati++; - } - - - - //If Target is a non-object and non-function (string or other type, it may be a deep copy) in if(typeofTarget!== "Object" &&!jquery.isfunction (target)) { -target = {}; to } + - //If there is only one argument, extend the jquery object itself the if(i = = =length) { *target = This; $i--;Panax Notoginseng } - for(; i < length; i++ ) { the //only non-null or undefined values are processed + if(options = arguments[i])! =NULL ) { A //To begin extending a base class object the for(Nameinchoptions) { +src =target[name]; -copy =options[name]; $ //prevents a circular chain, causing circular references $ if(target = = =copy) { - Continue; - } the //recursive jquery.extend If you want to perform a deep copy of a pure object or copy an array - Wuyi if(Deep && copy && jquery.isplainobject (copy) | | (Copyisarray =jquery.isarray (copy))) ) { the if(Copyisarray) { -Copyisarray =false; Wu - //Make sure that SRC is an array Aboutclone = src && jquery.isarray (src)?src: []; $}Else { - - //Make sure SRC is a pure object -clone = src && jquery.isplainobject (src)?src: {}; A } + //recursive call to Jquery.extend for deep copy thetarget[name] =jquery.extend (deep, clone, copy); - $ //Discard undefined value the}Else if(Copy!==undefined) { the //Execute Copy the thetarget[name] =copy; - } in } the } the } About //returning an extended object the returnTarget; the};
You can use the Jquery.extend method to extend the properties of jquery or other objects. For a pure object you can choose to perform a deep copy, and a deep copy must be performed for the array. Most of the functionality of jquery is extended in this way, or it can be a jquery extension. Jquery.extend ({}), when Target is Jquery.prototype, extends static properties or methods for jquery, which is also done internally by jquery. jquery (). Extend ({}), when Target is the jquery object itself, extend the property or method to the jquery object.
JQuery Source Analysis 4:jquery.extend