有时可能需要 JScript 没有提供的数据类型。在这种情况下,可以导入定义新类的包,或使用 class 语句创建自己的数据类型。类可以用于类型批注,并可使类型化数组与 JScript 中预定义的数据类型有完全相同的行为方式。
定义数据类型
下面的示例使用 class 语句定义了一种新的数据类型 - myIntVector。此新类型用在函数声明中,表示函数的参数类型。而且还使用此新类型批注了一个变量的类型。
// Define a class that stores a vector in the x-y plane. class myIntVector { var x : int; var y : int; function myIntVector(xIn : int, yIn : int) { x = xIn; y = yIn; } } // Define a function to compute the magnitude of the vector. // Passing the parameter as a user defined data type. function magnitude(xy : myIntVector) : double { return( Math.sqrt( xy.x*xy.x + xy.y*xy.y ) ); } // Declare a variable of the user defined data type. var point : myIntVector = new myIntVector(3,4); print(magnitude(point));
该代码的输出为:
5