共用方式為


使用者定義資料型別

更新:2007 年 11 月

有時候您會需要不是 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

請參閱

概念

型別附註

參考

class 陳述式

package 陳述式

其他資源

資料型別 (JScript)

JScript 物件