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 }