更新:2007 年 11 月
本主题演示如何在 ASP.NET 中创建 AJAX 客户端组件类。AJAX 客户端类(包括基组件、行为和控件类)是使用原型模型和 JSON 表示法在 ECMAScript (JavaScript) 中定义的。在 JSON 表示法中,所有的原型成员都用逗号隔开。原型中的最后一个成员后面没有逗号。
下面的示例定义一个不具有实际功能的简单客户端组件类。它演示如何使用原型模型来定义一个从 Component 基类派生的类。
// Declare a namespace. Type.registerNamespace("Samples"); // Define a simplified component. Samples.SimpleComponent = function() { Samples.SimpleComponent.initializeBase(this); // Initialize arrays and objects in the constructor // so they are unique to each instance. // As a general guideline, define all fields here. this._arrayField = []; this._objectField = {}; this._aProp = 0; } // Create protytype. Samples.SimpleComponent.prototype = { // Define set and get accessors for a property. Set_Aprop: function(aNumber) { this._aProp = aNumber; }, Get_Aprop: function() { return this._aProp; }, // Define a method. DoSomething: function() { alert('A component method was called.'); } } // End of prototype definition. // Register the class as derived from Sys.Component. Samples.SimpleComponent.registerClass('Samples.SimpleComponent', Sys.Component);
下面的步骤介绍如何定义一个 ASP.NET AJAX 客户端类(包括控件类)。:
-
如果该类是某个命名空间的一部分,则通过调用 Type.registerNamespace 方法来注册该命名空间。
-
在构造函数名中定义类的构造函数及其命名空间。在构造函数中,声明所有私有字段。推荐使用 this 指针将构造函数中的私有变量声明为实例字段。按照约定,私有字段的名称带有下划线前缀。
Samples.SimpleComponent = function() { Samples.SimpleComponent.initializeBase(this); this._arrayField = []; this._objectField = {}; this._aProp = 0; }
-
定义类原型。在原型中,定义所有公共和私有方法,其中包括属性访问器方法和事件。
建议在构造函数中定义所有字段。在原型中定义字段相对于在构造函数中定义字段能够获得非常小的性能提升。但是,并不是所有的字段类型都可以在原型中声明。例如,Array 和 Object 字段类型必须在构造函数中声明,这样它们对于每个实例都是唯一的,而不是在原型中从所有的实例中引用。这样可避免在针对一个实例更新组件属性时产生意外结果,以致更新所有实例的值。
说明:
始终通过 this 指针引用原型中的成员。使用 this 指针可以提高性能,因为工作集占用更少的内存。
-
通过调用 Type.registerClass 方法来注册类。有关如何使用 Type.registerClass 方法来注册一个类并声明该类的接口和基类的更多信息,请参见 Type.registerClass 方法。
