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
例如要创建一个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