命名空间:
Type.registerNamespace("MyNamespance");
--注册一个命名空间
类:
定义步骤
--定义构造函数
--定义成员(方法,属性,事件)
--注册类
构造函数
类的构造函数即为function定义
通常用于初始化域变量
私有成员使用下划线开头(无法真正封装)
--this._name
--this._age
MyNamespace.MyClass =functin(name,age)
{
this._name = name;
this._age = age;
}
定义方法:
基于prototype定义
-- MyNamespace.MyClass.prototype=
{
myMethod1:function()
{
},
myMethod2:function()
{
this.myMethod();//this保留字不可少
}
}
定义属性
--Microsoft AJAX Libray的面向对象类型系统set_和get_开头的方法认作属性
--避免定义只写属性,使用某个方法替代
MyNamespace.MyClass.prototype =
{
get_name:function()
{
retrun this._name;
},
set_name:funciton(value)
{
this._name = value;
}
}
注册类:
MyNamespace.MyClass.registerClass("MyNamespace.MyClass");
2
3<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4
5<script runat="server">
6
7</script>
8
9<html xmlns="http://www.w3.org/1999/xhtml" >
10<head runat="server">
11 <title>ASP.NET AJAX JavaSrciptOOP Class</title>
12</head>
13<body>
14 <form id="form1" runat="server">
15 <asp:ScriptManager ID="ScriptManager1" runat="server">
16 </asp:ScriptManager>
17 <script language="javascript" type="text/javascript" >
18
19 //注册一个命名空间
20 Type.registerNamespace("CL");
21
22 //定义一个类的构造方法
23
24 CL.Employee =function(eno,ename)
25 {
26 this._eno = eno;
27 this._ename = ename;
28 }
29
30 //定义方法和属性
31 CL.Employee.prototype =
32 {
33 get_eno:function()
34 {
35 return this._eno;
36 },
37 set_eno:function(value)
38 {
39 this._eno = value;
40 },
41 get_ename:function()
42 {
43 return this._ename;
44 },
45 set_ename:function(value)
46 {
47 this._ename = value;
48 },
49 toString:function()
50 {
51 return String.format("eno:{0} , ename:{1}",this.get_eno(),this.get_ename());
52 }
53 }
54 //注册这个类
55 CL.Employee.registerClass("CL.Employee");
56
57 //实例化
58 var emp = new CL.Employee();
59 //设置属性
60 emp.set_eno("NO.1");
61 emp.set_ename("张三");
62 //输出 会调用emp对象的toString方法
63 alert(emp);
64 </script>
65 <div>
66
67 </div>
68 </form>
69</body>
70</html>
71