Object-Oriented Programming/Properties/JavaScript
Appearance
index.js
[edit | edit source]// This program demonstrates use of the Temperature class.
const Temperature = require("./temperature");
main();
// Runs the main program.
function main() {
let temperature = new Temperature({celsius: 37});
console.log(temperature.fahrenheit);
temperature = new Temperature({fahrenheit: 98.6});
console.log(temperature.celsius);
temperature = new Temperature();
temperature.celsius = 37;
console.log(temperature.fahrenheit);
temperature = new Temperature();
temperature.fahrenheit = 98.6
console.log(temperature.celsius);
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:
// let temperature = new Temperature({celsius: 37});
// console.log(temperature.fahrenheit);
//
// temperature = new Temperature({fahrenheit: 98.6});
// console.log(temperature.celsius);
//
// temperature = new Temperature();
// temperature.celsius = 37;
// console.log(temperature.fahrenheit);
//
// temperature = new Temperature();
// temperature.fahrenheit = 98.6
// console.log(temperature.celsius);
//
// temperature = new Temperature();
// console.log(temperature.toCelsius(98.6));
// console.log(temperature.toFahrenheit(37));
//
// References:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set
// https://www.smashingmagazine.com/2016/07/how-to-use-arguments-and-parameters-in-ecmascript-6/
class Temperature
{
_celsius = undefined;
_fahrenheit = undefined;
constructor({celsius, fahrenheit} = {}) {
if (celsius != undefined) {
this.celsius = celsius;
}
if (fahrenheit != undefined) {
this.fahrenheit = fahrenheit
}
}
// Returns Celsius value.
get celsius() {
return this._celsius;
}
// Sets Celsius value.
set celsius(value) {
this._celsius = value;
this._fahrenheit = this.toFahrenheit(value);
}
// Returns Fahrenheit value.
get fahrenheit() {
return this._fahrenheit;
}
// Sets Fahrenheit value.
set fahrenheit(value) {
this._fahrenheit = value;
this._celsius = this.toCelsius(value);
}
// 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.
- Chapman.edu: Online JavaScript Interpreter
- CodeChef
- GDB Online
- Ideone
- JS.do
- paiza.IO
- PythonTutor
- repl.it