Jump to content

Programming Fundamentals/Objects/JavaScript

From Wikiversity

objects.js

[edit | edit source]
// This class converts temperature between Celsius and Fahrenheit.
// It may be used by assigning a value to either Celsius or Fahrenheit 
// and then retrieving the other value, or by calling the ToCelsius or
// ToFahrenheit methods directly.

class Temperature {
    constructor() {
        this._celsius = 0;
        this._fahrenheit = 32;
    }

    get celsius() {
        return this._celsius;
    }

    set celsius(value) {
        this._celsius = value;
        this._fahrenheit = this.toFahrenheit(value);
    }

    get fahrenheit() {
        return this._fahrenheit;
    }

    set fahrenheit(value) {
        this._fahrenheit = value;
        this._celsius = this.toCelsius(value);
    }

    toCelsius(fahrenheit) {
        return (fahrenheit - 32) * 5 / 9
    }

    toFahrenheit(celsius) {
        return celsius * 9 / 5 + 32
    }
}

// This program creates instances of the Temperature class to convert Celsius 
// and Fahrenheit temperatures.
//
// References:
//     https://www.mathsisfun.com/temperature-conversion.html
//     https://en.wikibooks.org/wiki/JavaScript

main()

function main() {
    var temp1 =  new Temperature();
    temp1.celsius = 0
    output("temp1.celsius = " + temp1.celsius);
    output("temp1.fahrenheit = " + temp1.fahrenheit);
    output("");

    temp1.celsius = 100;
    output("temp1.celsius = " + temp1.celsius);
    output("temp1.fahrenheit = " + temp1.fahrenheit);
    output("");
    
    var temp2 = new Temperature();
    temp2.fahrenheit = 0
    output("temp2.fahrenheit = " + temp2.fahrenheit);
    output("temp2.celsius = " + temp2.celsius);
    output("");

    temp2.fahrenheit = 100;
    output("temp2.fahrenheit = " + temp2.fahrenheit);
    output("temp2.celsius = " + temp2.celsius);
}

function output(text) {
    if (typeof document === 'object') {
      document.write(text);
    } 
    else if (typeof console === 'object') {
      console.log(text);
    } 
    else {
      print(text);
    }
}

Try It

[edit | edit source]

Copy and paste the code above into one of the following free online development environments or use your own JavaScript compiler / interpreter / IDE.

See Also

[edit | edit source]