在Javascript中模仿namepace。
下面我简单的用一段代码,创建一个多重对象函数,并属于windows对象。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<body>
<script type="text/javascript" >
function ns(pkg){//该函数,可以创建命名,空间,如果需要创建的对象已存在,则不清空它的值。
if(!pkg){
return null;
}
var arr=pkg.split(".");
var o=window[arr[0]]=window[arr[0]]||{};
var result=o;
var len=arr.length;
for(var i=1;i<len;i++){
o=o[arr[i]]=o[arr[i]]||{};
};
return result;
}
ns("com.momo.test");//注册一个命名空间,到window对象
com.momo.test.fn=function(){
alert(1);
};
alert(com.momo.test.fn);
com.momo.test.fn=function(){
alert(2);
};
alert(com.momo.test.fn);
</script>
</body>
</html>