//声明一个全局对象Namespace,用来注册命名空间 Namespace = new Object(); // 全局对象仅仅存在register函数,参数为名称空间全路径 Namespace.register = function(wk_NS) { var nsArray = wk_NS.split('.'); var sEval = ""; var sNS = ""; for (var i = 0; i < nsArray.length; i++) { if (i != 0) sNS += "."; sNS += nsArray[i]; sEval += "if (typeof(" + sNS + ") == 'undefined') " + sNS + " = new Object();" } if (sEval != "") eval(sEval); } /*** * test demo * Namespace.register("wk_test");注册命名空间 * wk_test.jquery=$;将$添加到该命名空间 * var p=wk_test.jquery("a").size();通过命名空间获取值 * alert(p); */
实例demo
-------------------------------------------------------------------------------------------------------------------------------------
<script type="text/javascript" src="namespace.js"></script> <script type="text/javascript" src="jquery-1.7.1.min.js"></script> <script type="text/javascript" src="jquery.validate.min.js"></script> <script type="text/javascript" > var data = "Core Selectors Attributes Traversing Manipulation CSS Events Effects Ajax Utilities".split(" "); Namespace.register("wk_vada"); wk_vada=$; wk_vada(document).ready(function() { wk_vada("#signupForm").validate({ rules: { name: "required", keyword:"required" }, messages: { name: "请输入姓名", keyword: "请输入姓名" } }); </script> <script type="text/javascript" src="jquery.autocomplete.min.js"></script> <script type="text/javascript" > Namespace.register("wk_auto"); wk_auto=$; wk_auto('#keyword').autocomplete(data).result(function(event, data, formatted) { alert(data); }); alert(wk_auto instanceof wk_vada); //false </script>
注:借鉴无私的开源者