介绍
jQuery.extend([deep], target, object1, [objectN])
用一个或多个其他对象来扩展一个对象,返回被扩展的对象。如果不指定target,则给jQuery对象本身进行扩展。这有助于插件作者为jQuery增加新方法。
参数
[deep],target,object1,[objectN]
deep:如果设为true,则递归合并。
target:待修改对象。
object1:待合并到第一个对象的对象。
objectN:待合并到第一个对象的对象。
合并对象
如果存在相同的结构,后面的对象会覆盖前面的对象值;
如果参数deep为 true,则会递归合并对象;
deep为 true
var result=$.extend( true, {},
{ name: "John", location: {city: "Boston",county:"USA"} },
{ last: "Resig", location: {state: "MA",county:"China"} } );
{ name: "John", location: {city: "Boston",county:"USA"} },
{ last: "Resig", location: {state: "MA",county:"China"} } );
我们可以看出object1中嵌套子对象location:{city:"Boston"}, object2中也嵌套子对象location:{state:"MA"},第一个深度拷贝参数为true,那么合并后的结果就是:
result={name:"John",last:"Resig",
location:{city:"Boston",state:"MA",county:"China"}}
location:{city:"Boston",state:"MA",county:"China"}}
反之省略第一个参数或者为false
var result=$.extend( false, {},
{ name: "John", location:{city: "Boston",county:"USA"} },
{ last: "Resig", location: {state: "MA",county:"China"} }
);
{ name: "John", location:{city: "Boston",county:"USA"} },
{ last: "Resig", location: {state: "MA",county:"China"} }
);
无target 扩展对象到jq对象本身
该方法就是将object1合并到jquery的全局对象中去,如:
$.extend({
hello:function(){alert('hello');}
});
hello:function(){alert('hello');}
});
完整代码:
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title></title> 6 <style> 7 8 </style> 9 </head> 10 <body> 11 12 <script src="jquery-3.0.0.min.js"></script> 13 <script> 14 15 //合并对象 false 16 var s= $.extend({},{name:'2',age:22},{name:'3',number:'232'},{limit:'23'}) 17 console.log(s); 18 19 // 合并对象 递归合并 true 20 var result=$.extend( true, {}, 21 { name: "John", location: {city: "Boston",county:"USA"} }, 22 { last: "Resig", location: {state: "MA",county:"China",age:'99'} } ); 23 console.log(result) 24 25 //扩展对象 26 $.extend({ 27 age:20,area:'上海', 28 hello:function(){ 29 console.log('20170817 hello') 30 } 31 } 32 ); 33 console.log($.age,$.area); 34 $.hello(); 35 36 </script> 37 </body> 38 </html>