js面向对象编程:命名空间


在其他语言中为了避免类和方法重名问题,都有一个类似命名空间的概念,在js中实现类似的功能吗?

   可以实现,主要是借助于js中对象的概念来实现,例如:

 1 在命名空间中定义方法属性

[javascript] view plain copy print ?
  1. var GiantCorp =GiantCorp||{};  
  2. GiantCorp.Common = {  
  3.     Test1:function(){alert("Test1")},//方法     
  4.      Field1:"Field1"//属性  
  5. };  
  6.   
  7. GiantCorp.ErrorCodes = {  
  8.       Test1:function(){alert("ErrorCodesTest1")},//方法     
  9.        Field1:"ErrorCodesField1"//属性       
  10. };  
var GiantCorp =GiantCorp||{};
GiantCorp.Common = {
    Test1:function(){alert("Test1")},//方法	
	 Field1:"Field1"//属性
};

GiantCorp.ErrorCodes = {
      Test1:function(){alert("ErrorCodesTest1")},//方法	
	   Field1:"ErrorCodesField1"//属性	 
};

调用方法:

[javascript] view plain copy print ?
  1. //测试代码  
  2.    function test(){   
  3.     GiantCorp.Common.Test1();  
  4.        alert(GiantCorp.Common.Field1);    
  5.        GiantCorp.ErrorCodes.Test1();  
  6.       alert(GiantCorp.ErrorCodes.Field1);     
  7.   
  8.   
  9.      var    Common=  GiantCorp.Common;//类似于引入命名空间  
  10.  Common.Test1();  
  11.       alert(Common.Field1);  
  12.   
  13.  }  
     //测试代码
        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在命名空间中定义类

[javascript] view plain copy print ?
  1. var GiantCorp =GiantCorp||{};  
  2. GiantCorp.obj=GiantCorp.obj||{};  
  3. GiantCorp.obj.Classobj =function(text1,text2){   //定义构造函数    
  4.         this.text1=text1;  
  5.          this.text2=text2;  
  6. }  
  7. GiantCorp.obj.Classobj.prototype.Do =function(){ //定义实例方法      
  8.       alert(this.text1+this.text2);  
  9. }  
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);
}

调用方法:

[javascript] view plain copy print ?
  1. //测试代码  
  2.        function test(){   
  3.          var obj=new  GiantCorp.obj.Classobj("测试1","测试2");          
  4.           obj.Do();//调用实例方法  
  5.           var   Classobj=  GiantCorp.obj.Classobj;//引入命名空间  
  6.           var obj2=new  Classobj("测试1","测试2");  
  7.           obj2.Do=function(text1,text2){ //重写实例方法      
  8.                alert(this.text1);  
  9.             }  
  10.          obj2.Do();//调用实例方法  
  11.      }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值