User-Defined Data Types

Sometimes you need a data type that is not provided by JScript. In this situation, you can import a package that defines a new class, or you can create your own data type using the class statement. Classes can be used for type annotation and for making typed arrays in exactly the same way as the predefined data types in JScript.

The following example uses the class statement to define a new data type, myIntVector. The new type is used in a function declaration to denote the type of the function's parameter. A variable is also type annotated with the new type.

// 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);

The output of this code is:


Community Additions