使用JScript.NET創(chuàng)建asp.net頁面(四)
2024-07-10 12:58:09
供稿:網(wǎng)友
 
在jscript中定義類通過類聲明, 包含方法和對象和var 聲明。對于類的派生通過下面兩個程序的對比,你講清楚地明白。
    jscript 5.5 code
// simple object with no methods
function car(make, color, year)
{
   this.make = make;
   this.color = color;
   this.year = year;
}
function car.prototype.getdescription()
{
   return this.year + " " + this.color + " " + this.make;
}
// create and use a new car object
var mycar = new car("accord", "maroon", 1984);
print(mycar.getdescription());
jscript.net code
// wrap the function inside a class statement.
class car
{
   var make : string;
   var color : string;
   var year : int;
   function car(make, color, year)
   {
      this.make = make;
      this.color = color;
      this.year = year;
   }
   function getdescription()
   {
      return this.year + " " + this.color + " " + this.make;
   }
}
var mycar = new car("accord", "maroon", 1984);
print(mycar.getdescription());
    jscript.net還支持定義private和protected property通過get和set進(jìn)行讀寫。
如下例:
class person
{
   private var m_sname : string;
   private var m_iage : int;
   function person(name : string, age : int)
   {
      this.m_sname = name;
      this.m_iage = age;
   }
   // name 只讀
   function get name() : string
   {
      return this.m_sname;
   }
   // age 讀寫但是只能用set
   function get age() : int
   {
      return this.m_sage;
   }
   function set age(newage : int)
   {
      if ((newage >= 0) && (newage <= 110))
         this.m_iage = newage;
      else
         throw newage + " is not a realistic age!";
   }
}
var fred : person = new person("fred", 25);
print(fred.name);
print(fred.age);
// 這將產(chǎn)生一個編譯錯誤,name是只讀的。
fred.name = "paul";
// 這個將正常執(zhí)行
fred.age = 26;
// 這將得到一個 run-time 錯誤, 值太大了
fred.age = 200;