HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

jQuery $.extend() Method

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.


1. Basic Object Merging

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 }

2. Deep Merging (Deep Copy)

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" } }
Safety Hint: $.extend(true, {}, original) is a common way to create a **perfect clone** of an object that won't affect the original when modified.

Practical Use Case: Plugin Defaults

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" });
Target Object: If you don't want to modify your default object, pass an empty object {} as the first target.

Key Points to Remember

  • $.extend() combines two or more objects into one.
  • The first object passed is the target (and it will be modified).
  • Properties from later objects overwrite earlier ones.
  • Use the true parameter to perform a recursive "deep merge."
  • It is the standard way to handle options and configuration in jQuery.