在JavaScript中應用Object (2)

來源:互聯網
上載者:User
  五. 對象應用常式
  再示範另一個關於Thermometer(溫度計)對象的例子,它負責將不同的溫度刻度進行轉換:
<script language="JavaScript">
// constructor
function Thermometer(degrees, scale)
{
// methods
this.convertToCelsius = convertToCelsius;
this.convertToFahrenheit = convertToFahrenheit;
this.raiseTemp = raiseTemp;
// action to take
if (scale == "f" || scale == "F")
    {
    this.scale = scale;
    this.degreesF = degrees;
    this.degreesC = 0;
    this.convertToCelsius();
 }
 else
    {
    this.scale = scale;
    this.degreesF = 0;
    this.degreesC = degrees;
    this.convertToFahrenheit();
    }
 }
// conversion functions
function convertToCelsius()
{
this.degreesC = (5.0/9.0) * (this.degreesF - 32.0);
}
function convertToFahrenheit()
{
this.degreesF = ((9.0/5.0) * this.degreesC) + 32.0;
}
// method to raise temperature
function raiseTemp(num)
{
this.degreesF += num;
this.degreesC += num;
}
</script>
  以上代碼的含義是:構造器建立了一個對象,用一個溫度和溫度刻度對其進行初始化,然後運行轉換函式來擷取在另一種刻度下等值的溫度。其中包含了一個 raiseTemp() 方法,以示範對象屬性是如何修改的。
  以下代碼示範了如何在 HTML 文檔中使用對象:
<script language="JavaScript">
// create an object instance
a = new Thermometer(98.6, "f");
// access object properties
alert("Temperature in Fahrenheit is " + a.degreesF);
alert("Temperature in Celsius is " + a.degreesC);
// execute object methods
a.raiseTemp(10);
alert("Temperature in Fahrenheit is " + a.degreesF);
alert("Temperature in Celsius is " + a.degreesC);
</script>
  
  六. 傳遞對象參數
  同可以向一個對象傳遞參數一樣,也可以把對象傳遞給另一個對象。請看看以下的例子,其中包含兩個物件建構器,設定第二個的目的是把一個對象作為參數來接收:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.