创建自己的类
更新:2007 年 11 月
class 语句定义类。默认情况下,类成员都可以公开访问,这就意味着任何可访问类的代码都可以访问类成员。有关更多信息,请参见 JScript 修饰符。
具有字段的类
字段定义对象所使用的数据,类似于基于原型的对象中的属性。下面是一个有两个字段的简单类的示例,使用 new 运算符来创建该类的一个实例:
class myClass {
const answer : int = 42; // Constant field.
var distance : double; // Variable field.
}
var c : myClass = new myClass;
c.distance = 5.2;
print("The answer is " + c.answer);
print("The distance is " + c.distance);
该程序的输出为:
The answer is 42
The distance is 5.2
具有方法的类
类还可以包含方法,方法是类中所包含的函数。方法定义操作对象数据的功能。可以重新定义前面已定义的 myClass 类,使之包含一个方法。
class myClass {
const answer : int = 42; // Constant field.
var distance : double; // Variable field.
function sayHello() :String { // Method.
return "Hello";
}
}
var c : myClass = new myClass;
c.distance = 5.2;
print(c.sayHello() + ", the answer is " + c.answer);
该程序的输出为:
Hello, the answer is 42
具有构造函数的类
可以为类定义构造函数。构造函数是与类有着相同名称的方法,当使用 new 运算符创建类时就运行构造函数。可以不指定构造函数的返回类型。在本示例中,向 myClass 类添加一个构造函数。
class myClass {
const answer : int = 42; // Constant field.
var distance : double; // Variable field.
function sayHello() :String { // Method.
return "Hello";
}
// This is the constructor.
function myClass(distance : double) {
this.distance = distance;
}
}
var c : myClass = new myClass(8.5);
print("The distance is " + c.distance);
该程序的输出为:
The distance is 8.5