Jump to content

Object-Oriented Programming/Methods/JavaScript

From Wikiversity

index.js

[edit | edit source]
// This program demonstrates use of the Temperature class.
//
// References:
//  * http://www.mathsisfun.com/temperature-conversion.html
//  * https://www.sitepoint.com/understanding-module-exports-exports-node-js/

const Temperature = require("./temperature");

main();

// Runs the main program.
function main() {
    var temperature = new Temperature();
    console.log(temperature.toCelsius(98.6));
    console.log(temperature.toFahrenheit(37));
}

temperature.js

[edit | edit source]
// Temperature converter. Provides temperature conversion functions. Supports Fahrenheit and Celius temperatures.
//
// Examples:
//    var temperature = new Temperature();
//    Console.WriteLine(temperature.ToCelsius(98.6));
//    Console.WriteLine(temperature.ToFahrenheit(37));
//
// References:
//  * http://www.mathsisfun.com/temperature-conversion.html
//  * https://www.sitepoint.com/understanding-module-exports-exports-node-js/

class Temperature
{
    // Converts Fahrenheit temperature to Celsius.
    toCelsius(fahrenheit) {
        return (fahrenheit - 32) * 5 / 9;
    }

    // Converts Celsius temperature to Fahrenheit.
    toFahrenheit(celsius) {
        return celsius * 9 / 5 + 32;
    }
}

module.exports = Temperature;

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]