用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()來註冊該類;