用prototype 方式来创建客户端组件类

用prototype mode有以下好处:
1、相对于那种把所有的方法定义都放在类的构造函数中的方式,这种方式的效率更高;
   采用prototype方式定义的类更容易理解,代码更好重用。一般来说比较推荐这种方式。当然了,这样的方式不是必须的,javascript的语法是十分的灵活的,正是由于他的灵活导致了许多代码的难以理解;
下面的代码是一个简单的prototype方式大示例:
// 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.

// Declare the base this class inherits from.
Samples.SimpleComponent.inheritsFrom(Sys.Component);

// Register the class as derived from Sys.Component.
Samples.SimpleComponent.registerClass('Samples.SimpleComponent', Sys.Component);


一般来说,采用prototype来定义一个类的步骤如下:
1、注册该类所在的名字空间Type.registerNameSpace()
2、定义这个类的构造函数
一般会在这个构造函数中定义这个类的field,field的定义方式是:
Samples.SimpleComponent = function()
{
    Samples.SimpleComponent.initializeBase(
this);
    
    
this._arrayField = [];
    
this._objectField = {};
    
this._aProp = 0;
}
就是要在前面加上this,然后是field的名字,field的名字一般以下划线开头;
3、定义这个class的prototpye;
在prototype的定义中,定义了该类的所有的方法,包括属性的getter和setter,
4、如果该类存在父类,在调用prototype定义之后,在调用Type.registerClass()之前;
5、调用Type.registerClass()来注册该类;
原文地址:https://www.cnblogs.com/strinkbug/p/589892.html