使用建構函式建立您自己的物件
更新:2007 年 11 月
JScript 的強大功能之一是能夠定義建構函式來建立自訂原型架構的物件,以便在您的指令碼中使用。若要建立原型架構物件的執行個體,您必須先定義建構函式。這個處理序會建立一個新物件,並且將它初始化、建立屬性 (Property) 以及指派初始值。完成時,建構函式會傳回一個參考到已建構的物件。在建構函式內,您可以使用 this 陳述式來參考所建立的物件。
含有屬性 (Property) 的建構函式
下列範例是為 pasta 物件定義建構函式的函式。this 陳述式允許建構函式初始化物件。
// pasta is a constructor that takes four parameters.
function pasta(grain, width, shape, hasEgg) {
this.grain = grain; // What grain is it made of?
this.width = width; // How many centimeters wide is it?
this.shape = shape; // What is the cross-section?
this.hasEgg = hasEgg; // Does it have egg yolk as a binder?
}
只要定義了物件建構函式,就能以 new 運算子建立該物件的執行個體。這裡的 pasta 建構函式是用來建立 spaghetti 和 linguine 物件。
var spaghetti = new pasta("wheat", 0.2, "circle", true);
var linguine = new pasta("wheat", 0.3, "oval", true);
您可以動態地將屬性 (Property) 加入至物件的執行個體中,但是這些變更只影響這個執行個體。
// Additional properties for spaghetti. The properties are not added
// to any other pasta objects.
spaghetti.color = "pale straw";
spaghetti.drycook = 7;
spaghetti.freshcook = 0.5;
如果您想不修改建構函式的函式就直接將一個額外的屬性 (Property) 加入至物件的所有執行個體中,請將這個屬性 (Property) 加入至建構函式的原型物件中。如需詳細資訊,請參閱進階的物件建立 (JScript)。
// Additional property for all pasta objects.
pasta.prototype.foodgroup = "carbohydrates";
含有方法的建構函式
要在物件的定義中包含方法 (函式) 是可能的。這項作業的執行方法之一是在建構函式中加入一個屬性 (Property),而該建構函式會參考其他地方定義的函式。這些函式和建構函式的函式一樣,也使用 this 陳述式來參考目前的物件。
下列範例在前面定義好的 pasta 建構函式上展開,以便包含函式顯示物件值時所要呼叫的 toString 方法 (使用物件時如果需要字串,通常 JScript 會使用物件的 toString 方法。您很少需要明確地呼叫 toString 方法)。
// pasta is a constructor that takes four parameters.
// The properties are the same as above.
function pasta(grain, width, shape, hasEgg) {
this.grain = grain; // What grain is it made of?
this.width = width; // How many centimeters wide is it?
this.shape = shape; // What is the cross-section?
this.hasEgg = hasEgg; // Does it have egg yolk as a binder?
// Add the toString method (defined below).
// Note that the function name is not followed with parentheses;
// this is a reference to the function itself, not a function call.
this.toString = pastaToString;
}
// The function to display the contents of a pasta object.
function pastaToString() {
return "Grain: " + this.grain + "\n" +
"Width: " + this.width + " cm\n" +
"Shape: " + this.shape + "\n" +
"Egg?: " + Boolean(this.hasEgg);
}
var spaghetti = new pasta("wheat", 0.2, "circle", true);
// Call the method explicitly.
print(spaghetti.toString());
// The print statement takes a string as input, so it
// uses the toString() method to display the properties
// of the spaghetti object.
print(spaghetti);
它會顯示下列的輸出內容。
Grain: wheat
Width: 0.2 cm
Shape: circle
Egg?: true
Grain: wheat
Width: 0.2 cm
Shape: circle
Egg?: true