在其他语言中为了避免类和方法重名问题,都有一个类似命名空间的概念,在js中实现类似的功能吗?
可以实现,主要是借助于js中对象的概念来实现,例如:
1 在命名空间中定义方法属性
var GiantCorp =GiantCorp||{};
GiantCorp.Common = {
Test1:function(){alert("Test1")},//方法
Field1:"Field1"//属性
};
GiantCorp.ErrorCodes = {
Test1:function(){alert("ErrorCodesTest1")},//方法
Field1:"ErrorCodesField1"//属性
};
调用方法:
//测试代码
function test(){
GiantCorp.Common.Test1();
alert(GiantCorp.Common.Field1);
GiantCorp.ErrorCodes.Test1();
alert(GiantCorp.ErrorCodes.Field1);
var Common= GiantCorp.Common;//类似于引入命名空间
Common.Test1();
alert(Common.Field1);
}
2在命名空间中定义类
var GiantCorp =GiantCorp||{};
GiantCorp.obj=GiantCorp.obj||{};
GiantCorp.obj.Classobj =function(text1,text2){ //定义构造函数
this.text1=text1;
this.text2=text2;
}
GiantCorp.obj.Classobj.prototype.Do =function(){ //定义实例方法
alert(this.text1+this.text2);
}
调用方法:
//测试代码
function test(){
var obj=new GiantCorp.obj.Classobj("测试1","测试2");
obj.Do();//调用实例方法
var Classobj= GiantCorp.obj.Classobj;//引入命名空间
var obj2=new Classobj("测试1","测试2");
obj2.Do=function(text1,text2){ //重写实例方法
alert(this.text1);
}
obj2.Do();//调用实例方法
}