JQuery命名空间与插件开发

参考网址:

http://blog.csdn.net/clerk0324/article/details/22498633  jQuery节点下进行命名空间的扩展

https://www.cnblogs.com/zikai/p/5074686.html  jQuery的extend的使用

https://zhidao.baidu.com/question/1643518843390350900.html  自定义命名空间



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
   <body>
  
  	<div id="div1"></div>
  	<script src="jquery.min.js"></script>
  	<script type="text/javascript">
  		$("#div1").html("<h1>hello</h1>");
  	</script>

  	<script type="text/javascript">
  		//类级别的插件开发
  		// 形式一
   		jQuery.bar = function(param) {   
			alert('This function takes a parameter, which is "' + param + '".');  
		};
		$.bar("hello");  
		// 形式二,这种形式扩展多个方法时,各方法用逗号分隔
		jQuery.extend({      
			foo: function() {      
				alert('This is a test. This is only a test.');      
			}
		});
  		$.foo(); 		
  	</script>

  	<script type="text/javascript">
  		// 对象级别的插件开发
  		// 形式一
  		(function($){ 
  			$.fn.bar2 = function(param){     
			     alert("this is bar2, "+param);     // Our plugin implementation code goes here.       
			};			
			$.fn.bar2("test2");  
		})(jQuery); 
		// 形式二,这种形式扩展多个方法时,各方法用逗号分隔
  		(function($){     
			$.fn.extend({
			bar3:function(param){     
			     alert("this is bar3, "+param);     // Our plugin implementation code goes here.       
			}      
			});  
			$.fn.bar3("test3"); 
		})(jQuery);   
		$.fn.bar2("test2"); // 这里依然可以调用bar2,bar3方法
  	</script>

  	<script type="text/javascript">
  		// https://www.cnblogs.com/zikai/p/5074686.html
  		// $.extend的使用
  		var a = {
  			id:3,
  			name:'hurricane'
  		};
  		var b = {
  			id:2,
  			age:30
  		};
  		var c = $.extend({},a,b);  		
  		var d = $.extend({},b,a); 		
  	</script>
  	
  	<script type="text/javascript">
  		// 简单的定义命名空间,有局限,适用于小型网站,不太可能出现命名空间冲突的情况
  		var aaa = {};
  		(function(){
  			aaa.sayHello = function(){
  				alert("aaa hello");
  			}
  		})
  		()
  		aaa.sayHello();
  		// 自定义命名空间,这样定义将拥有一个全局对象(将var com = {};
  		// 写在更顶级的文件中),提高了可重用性,并且可以更好地实现命名空间模块化
  		var com = {};
		$.defineNamespace = function () {
			var a = arguments, o = null, i, j, d;
			for (i = 0; i < a.length; i = i + 1) {
				d = a[i].split(".");
				// o = jQuery;
				o = com;
				for (j = (d[0] == "com") ? 1 : 0; j < d.length; j = j + 1) {
					o[d[j]] = o[d[j]] || {};
					o = o[d[j]];
				}
			}
			return o;
		};
  		(function(ns){
  			ns.sayHello = function(){
  				alert("com.hurricane hello");
  			}
  		})
  		($.defineNamespace("com.hurricane"))
  		com.hurricane.sayHello();
  		// tips mentioned above
  		console.log(null||{id:1,name:'hurricane'});// 用这种方法将null转变为对象
  	</script>
  </body>
</html>









猜你喜欢

转载自blog.csdn.net/hurricane_li/article/details/78907302