<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title> New Document </title>
<meta name="Generator" content="EditPlus">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<script src="jquery-1.9.1.js"></script>
</head>
<body>
</body>
</html>
<script>
//一、命名空间
var Namespace=new Object();
Namespace.register = function(path){
var arr = path.split(".");
var ns = "";
for(var i=0;i<arr.length;i++){
if(i>0) ns += ".";
ns += arr[i];
//eval执行动态js代码
eval("if(typeof(" + ns + ") == 'undefined') " + ns + " = new Object();");
}
}
Namespace.register("com.xcx.util");
Namespace.register("com.xcx.entity");
com.xcx.util.getName=function(){
alert("xcx");
}
com.xcx.util.getName();
com.xcx.entity.person = function(){
//变量作用域为函数内部,外部无法访问
var name = "default";
return {
getName : function(){
return name;
},
setName : function(newName){
name = newName;
},
chifan:function(){
alert("用手吃饭");
}
}
};
var person=com.xcx.entity.person();
/*alert(person.name);//直接访问,结果为undefined
alert(person.getName());
person.setName("pingping");
alert(person.getName());
person.chifan();*/
//二、jQuery闭包
(function ($) {
$.problemWo = function () { };
/*$.extend(dest,arg1,arg2,arg3……);
1、合并第二道第n个参数
2、如以下例子将会合并成{b:5,myclick:function(){alert("c");}},
特别地:agr1和arg2有相同的属性,后面的将会覆盖前面的属性
3、如果dest=true,则arg参数的子对象将会覆盖,dest=false子对象将会被舍去
*/
$.extend($.problemWo,
{ b: 5 },
{ myclick: function () { alert("c") }
}
);
})(jQuery);
var a=(function(){
var name="default";
return {getName:function(){alert("pingping");}};
})();
//a.getName();
//alert($.problemWo.b);
//$.problemWo.myclick();
//声明一个对象$.problemWo,添加一个a的实例属性和myclick的实例方法。
(function ($) {
$.problemWo = function () {
this.a = "abc"
};
$.extend($.problemWo.prototype,
{myclick: function () { alert(this.a); }}
);
})(jQuery);
var obj = new $.problemWo()
obj.myclick();
//判断全局变量是否定义,没有就抛出异常
if(typeof jQuery==="undefined")throw "没有引入jQuery.js文件";
if(typeof jquery==="undefined")throw "没有引入test.js文件";
</script>