JQuery的extend扩展方法有两种形式:
形式一:
jQuery.extend(target,[object1],[objectN])
这种中的target、object1、objectN都是Object类型。它的含义是将object1,objectN合并到target中,返回值为合并后的target,由此可以看出该方法合并后,是修改了target的结构的。如果想要得到合并的结果却又不想修改target的结构,可以如下使用下面:
var object = $.extend({}, object1, object2);
下面介绍一些例子:
<html> <head> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> </head> <body> <div id="log"></div> <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); var printObj = typeof JSON != "undefined" ? JSON.stringify : function(obj) { var arr = []; $.each(obj, function(key, val) { var next = key + ": "; next += $.isPlainObject(val) ? printObj(val) : val; arr.push( next ); }); return "{ " + arr.join(", ") + " }"; }; $("#log").append( printObj(object1) ); </script> </body> </html>
结果是:{"apple":0,"banana":{"price":200},"cherry":97,"durian":100}
<html> <head> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> </head> <body> <div id="log"></div> <script> 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); var printObj = typeof JSON != "undefined" ? JSON.stringify : function(obj) { var arr = []; $.each(obj, function(key, val) { var next = key + ": "; next += $.isPlainObject(val) ? printObj(val) : val; arr.push( next ); }); return "{ " + arr.join(", ") + " }"; }; $("#log").append( "<div><b>defaults -- </b>" + printObj(defaults) + "</div>" ); $("#log").append( "<div><b>options -- </b>" + printObj(options) + "</div>" ); $("#log").append( "<div><b>settings -- </b>" + printObj(settings) + "</div>" ); </script> </body> </html>
结果是:defaults -- {"validate":false,"limit":5,"name":"foo"}
options -- {"validate":true,"name":"bar"}
settings -- {"validate":true,"limit":5,"name":"bar"}
形式二:
jQuery.extend([deep], target, object1, [objectN])
其中deep是Boolean类型,target、object1、objectN是Object类型。它的含义是:如果deep设为true,则递归合并将object1,objectN合并到target中,返回值为合并后的target。
下面举个例子:
<html> <head> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> </head> <body> <div id="log"></div> <script> 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); var printObj = typeof JSON != "undefined" ? JSON.stringify : function(obj) { var arr = []; $.each(obj, function(key, val) { var next = key + ": "; next += $.isPlainObject(val) ? printObj(val) : val; arr.push( next ); }); return "{ " + arr.join(", ") + " }"; }; $("#log").append( printObj(object1) ); </script> </body> </html>
运行结果:{"apple":0,"banana":{"weight":52,"price":200},"cherry":97,"durian":100}