用prototype 方式來建立用戶端組件類

來源:互聯網
上載者:User
用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()來註冊該類;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.