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

    在其他语言中为了避免类和方法重名问题,都有一个类似命名空间的概念,在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();//调用实例方法
	     }




  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值