jQuery.extend函数用法

昨天把jquery插件部分重新看了一遍,发现jQuery.extend()这个函数使用比较高,现在将其用法整理如下:

1. 扩展jQuery类级全局方法:

1 $.extend({
2     trim:function(str){
3     str.replace(/^\s*/g,"");
4 }
5 });

2. 合并多个object对象

以jQuery.extend(css1,css2)为例,css1,css2对象有一些属性
extend函数会把css2有而css1没有的属性加到css1中,如果css2的某个属性与css1的某个属性名称享用,就会用css2的属性去覆盖css1的同名属性。css1就是最后的整和对象。或者也可以用 :
var newcss = jquery.extend(css1,css2)  newcss就是合并的新对象。
var newcss = jquery.extend({},css1,css2) newcss就是合并的新对象.而且没有破坏css1的结构。

1 //用法: jQuery.extend(obj1,obj2,obj3,..)
2 2var Css1={size: "10px",style: "oblique"}
3 3var Css2={size: "12px",style: "oblique",weight: "bolder"}
4 4$.jQuery.extend(Css1,Css2)
5 5//结果:Css1的size属性被覆盖,而且继承了Css2的weight属性
6 6// Css1 = {size: "12px",style: "oblique",weight: "bolder"}

3. 深度嵌套合并对象

新的extend()允许你更深度的合并镶套对象。下面的例子是一个很好的证明。

 1 // 以前的 .extend()   
 2  2   jQuery.extend(   
 3  3     { name: “John”, location: { city: “Boston” } },   
 4  4     { last: “Resig”, location: { state: “MA” } }   
 5  5   );   
 6  6    // 结果:   
 7  7    // => { name: “John”, last: “Resig”, location: { state: “MA” } }
 8  8  // 新的更深入的 .extend()   
 9  9   jQuery.extend( true,   
10 10   { name: “John”, location: { city: “Boston” } },   
11 11     { last: “Resig”, location: { state: “MA” } }   
12 12  );   
13 13  // 结果   
14 14   // => { name: “John”, last: “Resig”,   
15 15  //      location: { city: “Boston”, state: “MA” } }  

 

 

posted @ 2013-09-05 12:06  嘻哈披头士  阅读(126)  评论(0)    收藏  举报