The Extension Method extend of Jquery is a commonly used method in the process of writing plug-ins. This method has some heavy-load prototypes. Here, let's get to know about it.
The Extension Method prototype of Jquery is:
Extend (dest, src1, src2, src3 ...);
It means to merge src1, src2, src3... into the dest, and the returned value is the merged dest. It can be seen that the structure of the dest is modified after the method is merged. 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...) // "{}" is used as the dest parameter.
In this way, you can merge src1, src2, src3... and return the merged result 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 preceding parameter, the following parameter will overwrite the preceding parameter value.
You may have some knowledge about this function. Let's look at another official jquery example (http://api.jquery.com/jQuery.extend)
The Code is as follows:Copy codeThe Code is as follows: <! DOCTYPE html>
<Html>
<Head>
<Scriptsrc = "http://code.jquery.com/jquery-latest.js"> </script>
</Head>
<Body>
<Divid = "log"> </div>
<Script>
Var defaults = {validate: false, limit: 5, name: "foo "};
Var options = {validate: true, name: "bar "};
/* Merge defaults and options, without modifying defaults */
Var settings = $. extend ({}, defaults, options); // It is often used in Plug-in development.
VarprintObj = typeofJSON! = "Undefined "? JSON. stringify: function (obj ){
Vararr = [];
$. Each (obj, function (key, val ){
Varnext = key + ":";
Next + = $. isPlainObject (val )? PrintObj (val): val;
Arr. push (next );
});
Return "{" + arr. join (",") + "}";
};
$ ("# Log"). append ("<div> <B> defaults -- </B>" + printObj (defaults) + "</div> ");
$ ("# Log"). append ("<div> <B> options -- </B>" + printObj (options) + "</div> ");
$ ("# Log"). append ("<div> <B> settings -- </B>" + printObj (settings) + "</div> ");
</Script>
</Body>
</Html>
Output result:
Defaults -- {"validate": false, "limit": 5, "name": "foo"} // defaults is output as is
Options -- {"validate": true, "name": "bar"} // The Original output options
Settings -- {"validate": true, "limit": 5, "name": "bar"} // merge ults and options, if the following parameters have the same name as the preceding parameters, the following parameters will overwrite the preceding parameter values.