在其他語言中為了避免類和方法重名問題,都有一個類似命名空間的概念,在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();//調用執行個體方法 }