進階的類別建立

當定義 JScript 類別時,您可以指派屬性 (Property),這個定義的類別最後會繼承其他類別。 屬性是類別成員,類似於欄位,它可以加強控制資料的存取方式。 類別可以使用繼承來擴充 (或是將行為加入至) 其他類別。

您可以定義類別,讓它的執行個體支援 expando 屬性。 這表示類別架構的物件,可以動態將屬性和方法加入至物件中。 類別架構的 expando 物件所提供的某些功能,與原型架構的物件功能相同。

含有屬性的類別

JScript 使用 function getfunction set 陳述式來指定屬性。 您可以指定其中一個存取子 (或同時指定) 來建立唯讀、唯寫或讀取/寫入屬性,不過唯寫屬性很少使用,它可能表示類別設計上有問題。

呼叫程式會以存取欄位的方式來存取屬性。 最大的差別在於屬性必須使用 getter 和 setter 來存取,欄位則是直接存取。 屬性能讓類別檢查輸入的都是有效資訊、記錄屬性的讀取或設定次數、傳回動態資訊等。

屬性通常是用來存取類別的私用欄位或受保護的欄位。 私用欄位可以用 private 修飾詞來標記,只有類別的其他成員才能存取。 受保護的欄位可以用 protected 修飾詞來標記,只有這個類別或衍生類別的其他成員才能存取。 如需詳細資訊,請參閱 JScript 修飾詞

這個範例使用屬性來存取受保護的欄位。 保護欄位是為了幫助防止外部程式碼變更它的值,但可讓衍生類別存取。

class Person {
   // The name of a person.
   // It is protected so derived classes can access it.
   protected var name : String;

   // Define a getter for the property.
   function get Name() : String {
      return this.name;
   }

   // Define a setter for the property which makes sure that
   // a blank name is never stored in the name field.
   function set Name(newName : String) {
      if (newName == "")
         throw "You can't have a blank name!";
      this.name = newName;
   }
   function sayHello() {
      return this.name + " says 'Hello!'";
   }
} 

// Create an object and store the name Fred.
var fred : Person = new Person();
fred.Name = "Fred";
print(fred.sayHello());

本程式碼的輸出為:

Fred says 'Hello!'

如果把空白名稱指派給 Name 屬性,會產生錯誤。

從類別繼承

您可以使用 extends 關鍵字定義根據其他類別建置的類別。 JScript 可以擴充大部分與 Common Language Specification (CLS) 相容的類別。 使用 extends 關鍵字定義的類別稱為衍生類別,而所擴充的類別就稱為基底類別。

這個範例定義的新 Student 類別,是從前述範例的 Person 類別擴充而來。 Student 類別重新使用基底類別中定義的 Name 屬性,但是它定義新的 sayHello 方法來覆寫基底類別中的 sayHello 方法。

// The Person class is defined in the code above.
class Student extends Person {
   // Override a base-class method.
   function sayHello() {
      return this.name + " is studying for finals.";
   }
}

var mary : Person = new Student;
mary.Name = "Mary";
print(mary.sayHello()); 

本程式碼的輸出為:

Mary is studying for finals.

您在衍生類別中重新定義一個方法,並不會變更基底類別中對應的方法。

expando 物件

如果您只希望泛型物件是 expando,請使用 Object 建構函式。

// A JScript Object object, which is expando.
var o = new Object();
o.expando = "This is an expando property.";
print(o.expando);  // Prints This is an expando property.

如果您希望其中一個類別是 expando,請使用 expando 修飾詞來定義類別。 您只能使用索引 ([]) 附註來存取 expando 成員,不能使用點 (.) 附註來存取。

// An expando class.
expando class MyExpandoClass {
   function dump() {
      // print all the expando properties
      for (var x : String in this)
         print(x + " = " + this[x]);
   }
}
// Create an instance of the object and add some expando properties.
var e : MyExpandoClass = new MyExpandoClass();
e["answer"] = 42;
e["greeting"] = "hello";
e["new year"] = new Date(2000,0,1);
print("The contents of e are...");
// Display all the expando properites.
e.dump(); 

本程式的輸出為:

The contents of e are...
answer = 42
greeting = hello
new year = Sat Jan 1 00:00:00 PST 2000

請參閱

概念

JScript 修飾詞

建立您自己的類別

其他資源

類別架構的物件

JScript 物件