js物件導向編程:命名空間

來源:互聯網
上載者:User

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




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.