<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>在JavaScript中实现命名空间</title>
<script language="JavaScript">
Namespace = new Object();
// 全局对象仅仅存在register函数,参数为名称空间全路径,如"Grandsoft.GEA"
Namespace.register = function(fullNS)
{
// 将命名空间切成N部分, 比如Grandsoft、GEA等
var nsArray = fullNS.split('.');
var sEval = "";
var sNS = "";
for (var i = 0; i < nsArray.length; i++)
{
if (i != 0) sNS += ".";
sNS += nsArray[i];
// 依次创建构造命名空间对象(假如不存在的话)的语句
// 比如先创建Grandsoft,然后创建Grandsoft.GEA,依次下去
sEval += "if (typeof(" + sNS + ") == 'undefined') " + sNS + " = new Object();"
}
if (sEval != "") eval(sEval);
}
registerNamespace = function(nsName) {
var rootObject = window;
var namespaceParts = nsName.split('.');
for (var i = 0;i < namespaceParts.length; i++) {
var currentPart = namespaceParts[i];
if (!rootObject[currentPart]) {
rootObject[currentPart] = new Object();
}
rootObject = rootObject[currentPart];
}
}
// 注册命名空间Grandsoft.GEA, Grandsoft.GCM
registerNamespace("Grandsoft.GEA");
registerNamespace("Grandsoft.GCM");
与上面的效果一样的
//Namespace.register("Grandsoft.GEA");
//Namespace.register("Grandsoft.GCM");
// 在Grandsoft.GEA命名空间里面声明类Person
Grandsoft.GEA.Person = function(name, age)
{
this.name = name;
this.age = age;
}
// 给类Person添加一个公共方法show()
Grandsoft.GEA.Person.prototype.show = function()
{
alert(this.name + " is " + this.age + " years old!");
}
// 演示如何使用类Person
var p = new Grandsoft.GEA.Person("yanglf", 25);
p.show();
</script>
</head>
<body>
</body>
</html>