Home >Web Front-end >JS Tutorial >Detailed usage of jQuery.extend function_jquery

Detailed usage of jQuery.extend function_jquery

WBOY
WBOYOriginal
2016-05-16 17:52:101280browse

Jquery's extension method extend is a commonly used method when we write plug-ins. This method has some overloaded prototypes. Here, let's learn about it together.

Jquery’s extension method prototype is:

extend(dest,src1,src2,src3...);
It means to merge src1, src2, src3... In dest, 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 don't want to modify the structure of dest, you can use it as follows:
var newSrc=$.extend({},src1,src2,src3...)//That is, change "{}" as dest parameter.
In this way, src1, src2, src3... can be merged, and then the merged result will be returned to newSrc. For example:
var result=$.extend({},{name:"Tom",age:21},{name:"Jerry",sex:"Boy"})
Then the merged result
result={name:"Jerry",age:21,sex:"Boy"}
That is to say, if the following parameter has the same name as the previous parameter, then the latter parameter will overwrite the previous parameter value. .

Maybe you already have some understanding of this function. Let’s look at another official jquery example (http://api.jquery.com/jQuery.extend/)
The code is as follows:

Copy code The code is as follows:







<script> <br>var defaults ={validate:false,limit:5,name:"foo"}; <br>var options ={validate:true,name:"bar"}; <br>/* merge defaults and options, without modifying defaults */ <br>var settings =$.extend({},defaults,options); // Often used in plug-in development <br>varprintObj =typeofJSON !=" undefined"?JSON.stringify :function(obj){ <br>vararr =[]; <br>$.each(obj,function(key,val){ <br>varnext =key ": "; <br>next =$.isPlainObject(val)?printObj(val):val; <br>arr.push(next ); <br>}); <br>return"{ " arr.join(", ") " }"; <br>}; <br><br>$("#log").append("<div><b>defaults -- </b>" printObj(defaults) "</div>" ); <br>$("#log").append("<div><b>options -- </b>" printObj(options) "</div>"); <br>$ ("#log").append("<div><b>settings -- </b>" printObj(settings) "</div>"); <br></script>



The output result is:
defaults -- {"validate":false,"limit":5,"name": "foo"} //This is the original output defaults
options -- {"validate":true,"name":"bar"} //This is the original output options
settings -- {"validate": true,"limit":5,"name":"bar"} //Merge defaults and options. If the following parameters have the same name as the previous parameters, the latter ones will overwrite the previous parameter values.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn