js命名空间定义

   js虽说不具有像java等高级语言的面向对象特性,也没有像java语言定义命名空间那么容易,但是通过一些技巧完全可以实现js的面向对象编程,看起来还算是幽雅,呵呵。为了定义一个js类,我们首先要做的就是定义命名空间,就像java中定义一个类首先要定义包名一样重要,它可以有效防止类冲突。在js中我们是这样实现命名空间定义的:
    例如要创建一个Shape类,则需对应创建一个Shape.js文件,将该文件置于com/mycompany文件加下,在Shape.js中定义如下
      // Create the global symbol "com" if it doesn't exist
// Throw an error if it does exist but is not an object
var com;
if (!com) com = {};
else if (typeof com != "object")
    throw new Error("com already exists and is not an object");

// Repeat the creation and type-checking code for the next level
if (!com.mycompany) com.mycompany= {}
else if (typeof com.mycompany!= "object")
    throw new Error("com.mycompanyexists and is not an object");

// Throw an error if com.mycompany.Shape already exists
if (com.davidflanagan.Class)
    throw new Error("com.mycompany.Shape already exists");

// Otherwise, create and populate the namespace with one big object literal
com.mycompany.Shape= function(){
    this.init= function(data) { /* code here */ }
};

//also you can define other methods as many as you want
com.mycompany.Shape.prototype={
             method1:function(param1,param2){},
             method2:function(){}
               ....
}
以上就完成了一个命名空间为com.mycompany的Shape类定义,该类为Shape.js
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值