The $.extend() method is a powerful utility used to **merge** the contents of
two or more objects together into a single target object. It is essential for managing
configuration settings and building jQuery plugins.
When you merge two objects, properties from the second object will overwrite matching properties in the first (target) object.
var object1 = { apple: 0, banana: { weight: 52, price: 100 }, cherry: 97 };
var object2 = { banana: { price: 200 }, durian: 100 };
// Merge object2 into object1
$.extend(object1, object2);
// Resulting object1:
// { apple: 0, banana: { price: 200 }, cherry: 97, durian: 100 }
In the basic example above, notice that the weight property inside banana was
**lost**. To merge nested objects recursively, pass true as the first
argument.
var obj1 = { person: { name: "Alice", age: 25 } };
var obj2 = { person: { job: "Developer" } };
// Use 'true' for a deep merge
$.extend(true, obj1, obj2);
// Result: { person: { name: "Alice", age: 25, job: "Developer" } }
$.extend(true, {}, original) is a common way
to create a **perfect clone** of an object that won't affect the original when modified.
Most developers use $.extend() to merge user-provided settings with a set of
default options.
function myPlugin(userOptions) {
var defaults = {
color: "blue",
fontSize: "14px",
showBorder: true
};
// Merge user options into defaults safely
var settings = $.extend({}, defaults, userOptions);
console.log("Using color: " + settings.color);
}
// User only wants to change the color
myPlugin({ color: "red" });
{} as the first target.