返回值:ObjectjQuery.extend(target, [object1], [objectN])

Merge the contents of two or more objects together into the first object.

When we supply two or more objects to $.extend(), properties from all of the objects are added to the target object.

If only one argument is supplied to $.extend(), this means the target argument was omitted. In this case, the jQuery object itself is assumed to be the target. By doing this, we can add new functions to the jQuery namespace. This can be useful for plugin authors wishing to add new methods to JQuery.

Keep in mind that the target object (first argument) will be modified, and will also be returned from $.extend(). If, however, we want to preserve both of the original objects, we can do so by passing an empty object as the target:

var object = $.extend({}, object1, object2);

The merge performed by $.extend() is not recursive by default; if a property of the first object is itself an object or array, it will be completely overwritten by a property with the same key in the second object. The values are not merged. This can be seen in the example below by examining the value of banana. However, by passing true for the first function argument, objects will be recursively merged.

Undefined properties are not copied. However, properties inherited from the object's prototype will be copied over.

示例:

Merge two objects, modifying the first.

jQuery 代码:

var object1 = {
  apple: 0,
  banana: {weight: 52, price: 100},
  cherry: 97
};
var object2 = {
  banana: {price: 200},
  durian: 100
};

$.extend(object1, object2);
结果:
object1 === {apple: 0, banana: {price: 200}, cherry: 97, durian: 100}

示例:

Merge two objects recursively, modifying the first.

jQuery 代码:

var object1 = {
  apple: 0,
  banana: {weight: 52, price: 100},
  cherry: 97
};
var object2 = {
  banana: {price: 200},
  lime: 100
};

$.extend(true, object1, object2);
结果:
object1 === {apple: 0, banana: {weight: 52, price: 200}, cherry: 97, lime: 100}

示例:

Merge settings and options, modifying settings.

jQuery 代码:
var settings = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
jQuery.extend(settings, options);
结果:
settings == { validate: true, limit: 5, name: "bar" }

示例:

Merge defaults and options, without modifying the defaults. This is a common plugin development pattern.

jQuery 代码:
var empty = {}
var defaults = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
var settings = $.extend(empty, defaults, options);
结果:
settings == { validate: true, limit: 5, name: "bar" }
empty == { validate: true, limit: 5, name: "bar" }