一:基础
$.extend( target [, object1 ] [, objectN ] );
将o1和o2内容合并到target中,target可以为{},这样o1和o2.。。。值不变
例子
var result=$.extend({},{name:"Tom",age:21},{name:"Jerry",sex:"Boy"})
result={name:"Jerry",age:21,sex:"Boy"}
也可以省略target,只能传一个参数o1,即将o1绑到jquery对象本身上去,用于给jquery添加新的自定义函数,
例子
$.extend(test:function(){ alert("这就是扩展函数"); }); //调用方法: $.test();
延伸:$.fn.extend(src) 将src绑到jquery实例对象上 $.fn.extend(text:function(){ alert("只有jquery实例对象才可以调用额"); }); 用法:$("#id").text();
二:进阶默认deep=false,即非深度拷贝,o1、o2.。。。oN的第一层会添加、覆盖到target,有子对象的直接覆盖,子对象相当于一个值一样$.extend( [deep ], target, object1 [, objectN ] )
例子:
var result=$.extend( false, {}, { name: "John", location:{city: "Boston",county:"USA"} }, { last: "Resig", location: {state: "MA",county:"China"} } ); result={name:"John",last:"Resig",location:{state:"MA",county:"China"}}
若需要对子对象拷贝,实际上是在拷贝第一层后进入子对象继续拷贝,就像第一层一样,没有的就会加进去,已经有的会覆盖,实际$.extend()就是在进行加钙操作。例子
var result=$.extend( true, {}, { name: "John", location: {city: "Boston",county:"USA"} }, { last: "Resig", location: {state: "MA",county:"China"} } ); result={name:"John",last:"Resig", location:{city:"Boston",state:"MA",county:"China"}}