DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> jQuery入門知識 >> JQuery特效代碼 >> jquery 插件開發 extjs中的extend用法小結
jquery 插件開發 extjs中的extend用法小結
編輯:JQuery特效代碼     
在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"}
可以看到,其實是
extend(dest,src1,src2,src3...);
,將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的話,會出現在extend的結果
中。
2) 其他jquery extend的用法
1、$.extend(src)
  該方法就是將src合並到jquery的全局對象中去,如:
$.extend({ hello:function(){alert('hello');} });
  就是將hello方法合並到jquery的全局對象中。
  2、$.fn.extend(src)
  該方法將src合並到jquery的實例對象中去,如:
$.fn.extend({ hello:function(){alert('hello');} });
   就是將hello方法合並到jquery的實例對象中。
  下面例舉幾個常用的擴展實例:
$.extend({net:{}});
   這是在jquery全局對象中擴展一個net命名空間。
$.extend($.net,{ hello:function(){alert('hello');} })
  這是將hello方法擴展到之前擴展的Jquery的net命名空間中去。
3 深度復制
// 以前的 .extend()
jQuery.extend( false,
{ name: “John”, location: { city: “Boston” } },
{ last: “Resig”, location: { state: “MA” } }
);
// 結果:
// => { name: “John”, last: “Resig”, location: { state: “MA” } }
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 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 = 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"}
可以看到,extjs中使用的是apply,而desc居然在合拼的結果中丟掉了,因為ext js認為undefind的東西不應該出現在合拼的結果中了,認為是擦除掉原來的值了,這個要注意
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved