高级类创建

更新:2007 年 11 月

在定义 JScript 类时,可以为属性赋值,已定义的类可以随后从其他类继承这些属性。属性(像字段一样也是类成员)对数据的访问方式提供了更多控制。通过使用继承,一类可以扩展另一类(或在另一类上添加行为)。

可以定义一个类,使该类的实例支持 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 可扩展大多数符合公共语言规范 (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 对象