//Description: Merge the contents of two or more objects together into the first object.
//描述:合并2个或多个对象到第一个对象
//描述:合并2个或多个对象到第一个对象
jQuery.extend( [deep], target, object1 [, objectN] )
/*
-- deep If true, the merge becomes recursive (aka. deep copy).
deep 如果为true,那么合并就变成递归形式(可选的参数)
-- target The object to extend. It will receive the new properties.
target 指向要拓展的对象,它将接受新的属性
-- object1 An object containing additional properties to merge in.
object1 带有额外属性将要合并到target的对象
-- objectN Additional objects containing properties to merge in
跟object1一个屌样。
*/
//官方秘籍描述
When we supply two or more objects to $.extend(), properties from all of the objects are added to the target object.
//插两个对象(多几个也没关系的)到$.extend(),不论公母,这些对象都能很好的合体了。
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.
//只有一个对象插入extend()的时候,调用extend()的对象就无耻的变成了target来跟插入的对象合体,虽然这种行为很无耻,但是,日后,记住是日后,我们可以用这个特性来拓展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);
//快看,object1 就会被迫与 object2 进行合体!!因为object1被侵入了,所以,虽然外表看上去还是那个纯洁的object1(名字不变),实际上它的里面已经有了object2的东西了。函数返回后object就有了obj1和obj2的特性,实际上这样就是object = object1
//!!!重点来了!!! 有时候object1即想跟object2合体又想立个牌坊,想一直保持它原来的特性不变,地球人是很聪明的,发明了一种保护措施,就像下面这样
var object = $.extend({},object1, object2);//{}是空对象
//所以,如果想要保护object1,记得要采取保护措施,一定要带{},切记切记....
//下面这段看例子就非常明了
//Example one
//不进行递归合并
<script>
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);
//输出结果
object1: {"apple":0,"banana":{"price":200},"cherry":97,"durian":100}
//Example2
//递归合并
var object1 = {
apple: 0,
banana: {weight: 52, price: 100},
cherry: 97
};
var object2 = {
banana: {price: 200},
durian: 100
};
/* merge object2 into object1, recursively */
$.extend(true, object1, object2);
//输出结果
object1:{"apple":0,"banana":{"weight":52,"price":200},"cherry":97,"durian":100}
//!!!!!!!!!很重要!!!!!!!!!!!!!!!!!!
//文档中说 (Passing false for the first argument is not supported.)
//所以不要传 false 到第一个参数,要么放true要么什么也不放
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);
//输出结果
defaults -- {"validate":false,"limit":5,"name":"foo"}
options -- {"validate":true,"name":"bar"}
settings -- {"validate":true,"limit":5,"name":"bar"}