在 jQuery 裡,extend 在寫外掛時用得相當多。今天順便把 jQuery 與 Ext JS 的 extend 用法一起做個小結,先看 jQuery 的。
1)extend(dest, src1, src2, src3...)
var start = {
id: 123,
count: 41,
desc: 'this is information',
title: 'Base Object',
tag: 'uncategorized',
values: [1,1,2,3,5,8,13]};
var more = { name: 'Los Techies', tag: 'javascript'};
var extra = { count: 42, title: null, desc: undefined, values: [1,3,6,10]};
var extended = $.extend(start, more, extra);
console.log(JSON.stringify(extended));
輸出結果為:
{ "id": 123,
"count": 42,
"desc": "this is information",
"title": null,
"tag": "javascript",
"values": [1, 3, 6, 10],
"name": "Los Techies"}
可以看到,它會把 src1、src2、src3… 合併進 dest,回傳合併後的 dest,因此會「修改 dest 本身的結構」。若想取得合併結果卻不改動 dest,可以這樣用:
var newSrc = $.extend({}, src1, src2, src3...) //把 {} 當作 dest
例如:
var result = $.extend({}, {name:"Tom",age:21}, {name:"Jerry",sex:"Boy"})
// result = {name:"Jerry", age:21, sex:"Boy"}
也就是說,後面參數若與前面有同名屬性,會覆蓋前面的值。另外要注意:範例中 "desc": undefined 不會出現在結果裡(合併時仍保留 desc 原值),但 title:null 則會出現在結果中。
2、其他 jQuery extend 用法
1、$.extend(src):把 src 合併到 jQuery 全域物件中,如:
$.extend({ hello:function(){alert('hello');} }); //把 hello 加入全域物件
2、$.fn.extend(src):把 src 合併到 jQuery 的實例物件中,如:
$.fn.extend({ hello:function(){alert('hello');} }); //把 hello 加入實例物件
常用的擴充範例:
$.extend({net:{}}); //在全域物件中擴充 net 命名空間
$.extend($.net, { hello:function(){alert('hello');} }); //把 hello 放進 net 命名空間
3、深度複製(deep copy):
// 淺拷貝(false)
jQuery.extend( false,
{ name: "John", location: { city: "Boston" } },
{ last: "Resig", location: { state: "MA" } }
);
// => { name: "John", last: "Resig", location: { state: "MA" } }
// 深拷貝(true)
jQuery.extend( true,
{ name: "John", location: { city: "Boston" } },
{ last: "Resig", location: { state: "MA" } }
);
// => { name: "John", last: "Resig", location: { city: "Boston", state: "MA" } }
3)如果是 Ext JS,又有什麼不同?
var extended = Ext.apply(start, more, extra);
console.log(JSON.stringify(extended));
輸出:
{ "id": 123, "count": 42, "title": null, "tag": "javascript", "values": [1,3,6,10], "name": "Los Techies"}
差別在於:Ext JS 用的是 apply,而且 desc 竟然在合併結果中消失了——因為 Ext JS 認為 undefined 的東西不該出現在結果中,等同於把原值擦除掉,這點要特別留意。