Jquery Explanation of extend function usage

Extension method of JQuery:
The extension method extend of Jquery is a common method in the process of writing plug-ins. This method has some overloaded prototypes. Here, let's learn about it.
* * I. the extension method prototype of Jquery is: **


It means that src1,src2,src3 Merge it into DeST, and the return value is the merged dest. It can be seen that this method modifies the structure of DeST after merging. If you want to get the merged result but do not want to modify the dest structure, you can use the following:

var newSrc=$.extend({},src1,src2,src3...)//That is, take "{}" as the dest parameter.

In this way, src1,src2,src3 Merge, and then return the merged result to newSrc. The following example:

var result=$.extend({},{name:"Tom",age:21},{name:"Jerry",sex:"Boy"})

Then the consolidated results


That is, if the following parameters have the same name as the previous parameters, the latter will overwrite the previous parameter values.

2, Omit dest parameter
The dest parameter in the above extend method prototype can be omitted. If omitted, the method can only have one src parameter, and the src is merged into the object calling the extend method, such as:
**This method is to merge src into the global object of jquery, such as:


Is to merge the hello method into the global object of jquery.
This method merges src into the instance object of jquery, such as:


Is to merge the hello method into the instance object of jquery.

Here are some common extension examples:


This is to extend a net namespace in the jquery global object.


This is to extend the hello method to the net namespace of the previously extended Jquery.

III. The extend method of Jquery also has an overload prototype:


The first parameter, boolean, represents whether to perform deep copy. The other parameters are the same as those described above. What is deep copy? Let's take an example:

var result=$.extend( true, {},  
{ name: "John", location: {city: "Boston",county:"USA"} },  
{ last: "Resig", location: {state: "MA",county:"China"} } );

We can see that the sub object location:{city: "Boston"} is embedded in src1, and the sub object location:{state:"MA"} is embedded in src2. The first deep copy parameter is true, so the combined result is:


That is to say, it will also merge nested sub objects in src. If the first parameter boolean is false, let's see the result of merging, as follows:

var result=$.extend( false, {},  
{ name: "John", location:{city: "Boston",county:"USA"} },  
{ last: "Resig", location: {state: "MA",county:"China"} }  

The combined result is:


That's $ Some details of extend() that are often used in projects.
Source: https://www.cnblogs.com/zikai/p/5074686.html

Tags: JQuery

Posted by anne on Thu, 02 Jun 2022 01:31:42 +0530