如何避免JavaScript中的名称空间污染?
避免命名空间污染
Javascript 不支持 函数重载。因此,当使用两个具有相同名称的函数时,一个函数将根据另一个函数的加载顺序来覆盖另一个函数。这意味着javascript缺少命名空间(命名约定)。但是,我们可以使用对象创建命名空间,从而避免名称冲突。
var Tutorix = Tutorix || {};上面的代码行指出,如果Tutorix 对象已经存在,则使用它,否则创建一个新对象。
我们还可以创建嵌套的命名空间,该命名空间是另一个命名空间内的命名空间。
var Tutorix = Tutorix || {};
Tutorix.TeamA1 = Tutorix.TeamA1 || {};在上面的代码行中,第二行建议如果TeamA1 已经存在,请使用该对象,否则创建一个空的TeamA1 对象。
在下面的示例中,即使我们仅在HTML文件中传递2个参数,我们在输出中也获得3个参数。这是由于Team1和Team2之间发生的命名空间冲突(两者共享相同的功能名称“student”)。
TeamA1.js
<html>
<body>
<script>
function student(Fname,Lname){
this.Fname = Fname;
this.Lname = Lname;
This.getFullName = function(){
return this.Fname + " " + this.Lname;
}
}
</script>
</body>
</html>TeamA2.js
<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文件
<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个参数“Rajendraprasadundefined”。这是因为TeamA2.js其中有3个参数已经覆盖了TeamA1.js。
因此,为了避免这种类型的名称冲突,我们必须使用对象创建命名空间。
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.js
在下面的代码命名空间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文件
在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 以避免名称冲突。由于避免了命名空间冲突,因此我们获得了每个单独脚本的输出。
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短