Javascript 不支持 函数重载。因此,当使用两个具有相同名称的函数时,一个函数将根据另一个函数的加载顺序来覆盖另一个函数。这意味着javascript缺少命名空间(命名约定)。但是,我们可以使用对象创建命名空间,从而避免名称冲突。
var Tutorix = Tutorix || {};上面的代码行指出,如果Tutorix 对象已经存在,则使用它,否则创建一个新对象。
我们还可以创建嵌套的命名空间,该命名空间是另一个命名空间内的命名空间。
var Tutorix = Tutorix || {};
Tutorix.TeamA1 = Tutorix.TeamA1 || {};在上面的代码行中,第二行建议如果TeamA1 已经存在,请使用该对象,否则创建一个空的TeamA1 对象。
在下面的示例中,即使我们仅在HTML文件中传递2个参数,我们在输出中也获得3个参数。这是由于Team1和Team2之间发生的命名空间冲突(两者共享相同的功能名称“ student ”)。
<html>
<body>
<script>
function student(Fname,Lname){
this.Fname = Fname;
this.Lname = Lname;
This.getFullName = function(){
return this.Fname + " " + this.Lname;
}
}
</script>
</body>
</html><html>
<body>
<script>
function student(Fname, Mname, Lname){
this.Fname = Fname;
this.Mname = Mname;
this.Lname = Lname;
This.getFullName = function(){
return this.Fname + " " + this.Mname + " " + this.Lname;
}
}
</script>
</body>
</html><html>
<head>
<script type = "javascript" src = "TeamA1.js"></script>
<script type = "javascript" src = "TeamA2.js"></script>
</head>
<body>
<div id = "resultDiv"></div>
<script>
document.getElementById("resultDiv").innerHTML =
new student("Rajendra", "prasad").getFullName();
</script>
</body>
</html>Rajendra prasad undefined.
由于在TeamA1.js和TeamA2.js之间发生命名空间冲突,即使我们仅发送2个参数“ Rajendra”和“ prasad”以访问TeamA1.js,我们在输出中仍得到3个参数“ Rajendra prasad undefined”。这是因为TeamA2.js其中有3个参数已经覆盖了TeamA1.js。
因此,为了避免这种类型的名称冲突,我们必须使用对象创建命名空间。
在下面的代码命名空间TeamA1 使用称为另一对象而创建Tutorix。
<html>
<body>
<script>
var Tutorix = Tutorix || {};
Tutorix.TeamA1 = Tutorix.TeamA1 || {};
Tutorix.TeamA1.student = function (Fname, Lname){
this.Fname = Fname;
this.Lname = Lname;
this.getFullName = function(){
return this.Fname + " " + this.Lname;
}
return this;
}
</script>
</body>
</html>在下面的代码命名空间TeamA2 使用称为另一对象而创建Tutorix。
<html>
<body>
<script>
var Tutorix = Tutorix || {};
Tutorix.TeamA2 = Tutorix.TeamA2 || {};
Tutorix.TeamA2.student = function (Fname, Mname, Lname){
this.Fname = Fname;
this.Mname = Mname;
this.Lname = Lname;
this.getFullName = function(){
return this.Fname + " " + this.Mname + " " + this.Lname;
}
return this;
}
</script>
</body>
</html>在HTML文件中包括两个js文件(TeamA1.js和TeamA2.js)。
<html>
<head>
<script type = "javascript" src = "TeamA1.js"></script>
<script type = "javascript" src = "TeamA2.js"></script>
</head>
<body>
<script>
document.write(window.Tutorix.TeamA1.student("Rajendra", "prasad").getFullName());
document.write(window.Tutorix.TeamA2.student("Babu","Rajendra","prasad").getFullName());
</script>
</body>
</html>Rajendra prasad Babu Rajendra prasad
在上面的示例中,我们使用了 嵌套的命名空间,在Tutorix 命名空间中,我们嵌套了TeamA1 和TeamA2 以避免名称冲突。由于避免了命名空间冲突,因此我们获得了每个单独脚本的输出。