jQuery Extend()
The jQuery extend()
method is used to merge the properties of two or more objects into the first object. It is commonly used to create new objects or to extend the functionality of existing ones.
Key Topics
Basic Usage of extend()
The extend()
method merges the properties of one object into another.
var obj1 = { name: "John", age: 30 };
var obj2 = { city: "New York" };
var merged = $.extend(obj1, obj2);
console.log(merged); // Output: { name: "John", age: 30, city: "New York" }
Explanation: This code merges the properties of obj2
into obj1
, resulting in a single object containing properties from both.
Deep Merging with extend()
Use extend()
with the first argument set to true
to perform a deep merge, ensuring that nested objects are merged rather than overwritten.
var obj1 = { person: { name: "John", age: 30 } };
var obj2 = { person: { city: "New York" } };
var deepMerged = $.extend(true, {}, obj1, obj2);
console.log(deepMerged); // Output: { person: { name: "John", age: 30, city: "New York" } }
Explanation: This code merges the nested person
objects from obj1
and obj2
into a new object without overwriting existing nested properties.
Example: Using extend()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Extend Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div>
<p>Check the console for the merge results.</p>
</div>
<script>
$(document).ready(function() {
var defaults = { color: "blue", size: "medium" };
var userSettings = { size: "large", font: "Arial" };
var settings = $.extend({}, defaults, userSettings);
console.log("Merged Settings:", settings);
// Output: { color: "blue", size: "large", font: "Arial" }
});
</script>
</body>
</html>
Explanation: This example uses extend()
to merge default settings with user-defined settings, resulting in a configuration object that incorporates both.
Key Takeaways
- Object Merging: Use
extend()
to combine properties from multiple objects into one. - Deep Merge: Perform deep merging by passing
true
as the first argument. - Custom Defaults: Useful for creating configuration objects with default values and user overrides.