Jump to content

Programming Fundamentals/Object Examples JavaScript

From Wikibooks, open books for an open world

Objects

[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);
   }
 }

Output

[edit | edit source]
temp1.celsius = 0
temp1.fahrenheit = 32

temp1.celsius = 100
temp1.fahrenheit = 212

temp2.fahrenheit = 0
temp2.celsius = -17.77777777777778

temp2.fahrenheit = 100
temp2.celsius = 37.77777777777778

References

[edit | edit source]