jQuery extend 命名空间 each 等讲解

1.extend 扩展

  ① 基本扩展

extend(dest,src1,src2,src3...);
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"
 
  

  ② 省略dest参数

 $.extend({
  hello:function(){alert('hello');}
  });//合并到jQuery全局对象中
$.fn.extend({
  hello:function(){alert('hello');}
 });//合并到jQuery实例对象中

   //比较

  ③ 基本扩展和深入扩展

//基本扩展;
 var newSrc1 = jQuery.extend(   
    { name: "jonh", location: { city: "Boston" } },   
    { last: "Resig", location: { state: "MA" } }   
  );  
 alert(newSrc1.location.city); 
 
//深入扩展;
   var newSrc2 = jQuery.extend( true,   
  { name: "John", location: { city: "Boston" } },   
    { last: "Resig", location: { state: "MA" } }   
 ); 
   alert(newSrc2.location.city);
 深入扩展后,location中的属性变成了两个,而基本扩展确实覆盖

2.命名空间

  ① net 中有json数据

 $.extend({net:[{name:"ggf"},{name:"jack"}]});
   $.extend($.net,{
    hello:function(){alert('hello');}
   });
   $(document).ready(function(){$.net.hello();alert($.net[1].name);});
  ② net 中没有json数据
 $.extend({net:{}});
   $.extend($.net,{
    hello:function(){alert('hello');}
   });
   $(document).ready(function(){$.net.hello();alert($.net[1].name);});

3.jQuery each 函数

$.each([1,2,3],function(i,val){
	//var 就是循环到的实体;
	//alert(i);次数
	//alert(val);值
});
var obj = { one:"o", two:"t", three:"r", four:"f"};     
$.each(obj, function(key, val) {    
	//alert(val.one);error
    //alert(val.key);error
    //alert(obj.key);error
    //alert(obj.one);o o o o 
     //alert(key);  one two three four
     //alert(val);o t r f
}); 
var obj2 = [{name:"Jack",age:22},{name:"Marry",age:21}];
$.each(obj2, function(key, val) { 
	//alert(key);1 2
	//alert(val.name);Jack Marry
	//alert(obj2[1].age);
}); 
}

你可能感兴趣的:(jQuery)