JS Object-Oriented Programming: namespaces

Source: Internet
Author: User

In other languages in order to avoid the problem of class and method name, there is a similar namespace concept, in JS to achieve similar functionality?

Can be achieved, mainly by the use of the concept of JS object, such as:

1 Defining method Properties in a namespace

var Giantcorp =giantcorp| | {}; Giantcorp.common = {    test1:function () {alert ("Test1")},//method Field1: "Field1"//attribute}; Giantcorp.errorcodes = {      test1:function () {alert ("ErrorCodesTest1")},//method   Field1: "ErrorCodesField1"//attribute};

Call Method:

     Test Code        Function test () {        GiantCorp.Common.Test1 ();            alert (GiantCorp.Common.Field1);            GiantCorp.ErrorCodes.Test1 ();           alert (GiantCorp.ErrorCodes.Field1);               The Var common=  giantcorp.common;//is similar to introducing a namespace    common.test1 ();           alert (common.field1);     }

2 Defining a class in a namespace

var Giantcorp =giantcorp| | {}; giantcorp.obj=giantcorp.obj| | {}; GiantCorp.obj.Classobj =function (text1,text2) {   //define constructor          This.text1=text1;     THIS.TEXT2=TEXT2;} GiantCorp.obj.Classobj.prototype.Do =function () {//Define instance Method          alert (THIS.TEXT1+THIS.TEXT2);}

Call Method:

Test the Code        function test () {     var obj=new  GiantCorp.obj.Classobj ("Test 1", "Test 2");    Obj. Do ();//Call instance method  var classobj=  giantcorp.obj.classobj;//introduce  the namespace var obj2=new  classobj ("Test 1", "Test 2");      Obj2. Do=function (TEXT1,TEXT2) {//Override instance Method                    alert (THIS.TEXT1);             } obj2. Do ();//Invoke instance method     }




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.