首先申明:本文很多的内容,都是从网上摘抄过来的,主要是为了完善自己为公司做的培训网站.. 客户端编程 本篇主要讲解ajax的客户端面向对象编程 Sys.Type类 Type.registerNamespace("命名空间的名称"); classInstanceVar.registerClass("类名称", 基类(可选), 接口(可选,多个就顺序写下去)); typeInstanceVar.registerInterface("接口名称"); ANamespace.AnEnum.registerEnum("枚举名称"); typeVar.initializeBase(初始化基类的实例(一般是this), [传值给基类构造函数的参数](可选) ); (返回值为基类的实例) instanceVar.callBaseMethod(调用基类方法的实例(一般是this), "基类的方法名称", [传值给基类方法的参数](可选)); 代码示例 // 注册一个名为“Demo”的命名空间 Type.registerNamespace("Demo"); // 定义Demo命名空间下的Message类的构造函数 Demo.Message = function(content, publishTime) { //默认以下化线的为private属性 this._content = content; this._publishTime = publishTime; } // 定义Demo命名空间下的Message类的方法 Demo.Message.prototype = { get_content: function() { return this._content; }, get_publishTime: function() { return this._publishTime.format("yyyy-MM-dd HH:mm:ss"); }, toString: function() //覆盖了基类object的方法 { return this.get_content() + " " + this.get_publishTime(); } } // 在Demo命名空间下注册Message类(实在搞不懂为什么要先定义类然后在注册。。) Demo.Message.registerClass('Demo.Message'); // 定义在Demo命名空间下的IContent接口(接口不能有构造函数) Demo.IContent = function() { } // 定义Demo命名空间下的IContent接口的方法 Demo.IContent.prototype = { showContent : function() { } } // 在Demo命名空间下注册IContent接口 Demo.IContent.registerInterface('Demo.IContent'); // 定义Demo命名空间下的MessageWithUserId类的构造函数 // 我们之后要让这个类继承自Demo.Message // 在构造函数内用initializeBase调用基类的构造函数 Demo.MessageWithUserId = function(userId, content, publishTime) { Demo.MessageWithUserId.initializeBase(this, [content, publishTime]); this._userId = userId; } // 定义Demo命名空间下的MessageWithUserId类的方法 Demo.MessageWithUserId.prototype = { get_userId: function() { return this._userId; }, showContent: function() { return Demo.MessageWithUserId.callBaseMethod(this, 'get_content') }, // callBaseMethod用于调用基类的方法 toString: function() { return this.get_userId() + " " + Demo.MessageWithUserId.callBaseMethod(this, 'toString'); } } // 在Demo命名空间下注册MessageWithUserId类 // 他继承自Demo.Message类和Demo.IContent接口 Demo.MessageWithUserId.registerClass('Demo.MessageWithUserId', Demo.Message, Demo.IContent); // 定义在Demo命名空间下的Color枚举(枚举不能有构造函数) Demo.Color = function() { } // 定义Demo命名空间下的Color枚举的成员 Demo.Color.prototype = { // “0x”代表16进制,eval一下就会变成10进制的整型 Red: 0xFF0000, Blue: 0x0000FF, Green: 0x00FF00, White: 0xFFFFFF } // 在Demo命名空间下注册Color枚举 Demo.Color.registerEnum("Demo.Color"); // 只有对异步回发才需要向脚本文件中的 Sys.Application.notifyScriptLoaded 方法添加调用 // 建议在每一个js文件的结尾处都应该包括如下这句 // 通知ScriptManager这段脚本已经加载完毕 if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded(); 使用介绍 var testMessage = new Demo.Message('hello', d); alert(testMessage.get_content() + " " + testMessage.get_publishTime()); alert(testMessage); 如果如上的javascript定义在一个文件内,则需要引入该文件。如果是ScriptManager 控件,则需要这样设置: <Scripts> <asp:ScriptReference path="MyScript.js" /> </Scripts> 相关文章: