進階的物件建立 (JScript)

更新:2007 年 11 月

JScript 支援以自訂原型架構的物件來繼承。原型架構的物件可以經由繼承來共用一組能夠動態加入或刪除的常用屬性 (Property) 和方法。此外,個別的物件也能覆寫預設行為。

建立原型架構的物件

若要建立原型架構物件的執行個體,您必須先定義建構函式 (Constructor Function)。如需詳細資訊,請參閱使用建構函式建立您自己的物件。一旦建構函式撰寫完成,您可以使用 prototype 物件的屬性,來建立繼承的屬性和共用方法,其中該物件的屬性本身就是每個建構函式的屬性。建構函式可以為物件提供執行個體特定的資訊,prototype 物件可以為物件提供物件特定的資訊和方法。

注意事項:

若要影響物件的所有執行個體,就必須變更建構函式的 prototype 物件。變更物件中某個執行個體的 prototype 屬性,並不會影響該物件中其他的執行個體。

由於 prototype 物件的屬性和方法是以參考的方式複製到物件的每個執行個體,因此所有執行個體都能存取相同的資訊。您可以變更某個執行個體中的原型屬性值來覆寫預設值,但這項變更只影響這個執行個體。下列範例使用自訂建構函式 Circle。this 陳述式讓這個方法可以存取物件的成員。

// Define the constructor and add instance specific information.
function Circle (radius) {
    this.r = radius;  // The radius of the circle.
}
// Add a property the Circle prototype.
Circle.prototype.pi = Math.PI;
function ACirclesArea () {
   // The formula for the area of a circle is pi*r^2.
   return this.pi * this.r * this.r; 
}
// Add a method the Circle prototype.
Circle.prototype.area = ACirclesArea;
// This is how you would invoke the area function on a Circle object.
var ACircle = new Circle(2);
var a = ACircle.area();

您可以使用這個原則來為現有建構函式 (它們全都有原型物件) 定義其他的屬性。快速模式關閉時,才能運作。如需詳細資訊,請參閱 /fast

例如,如果您希望能移除字串前後的空白 (類似 Visual Basic 中的 Trim 函式),便可以在 String 原型物件上建立自己的方法,然後指令碼中的所有字串就會自動繼承此方法。這個範例使用規則運算式常值來移除空格。如需詳細資訊,請參閱規則運算式物件

// Add a function called trim as a method of the prototype 
// object of the String constructor.
String.prototype.trim = function() {
   // Use a regular expression to replace leading and trailing 
   // spaces with the empty string
   return this.replace(/(^\s*)|(\s*$)/g, "");
}

// A string with spaces in it
var s = "    leading and trailing spaces    ";
print(s + " (" + s.length + ")");

// Remove the leading and trailing spaces
s = s.trim();
print(s + " (" + s.length + ")");

使用 /fast- 旗標編譯這個程式後,這個程式的輸出為:

    leading and trailing spaces     (35)
leading and trailing spaces (27)

請參閱

其他資源

原型架構的物件

JScript 物件