Since ES6, JavaScript now supports classes. They are not based on an object-oriented inheritance model. Classes are still functions. They sit on top of JavaScript’s prototype inheritance.
A class contains a set of properties that define an object.
The following is an example of a class in JavaScript:
class Potholder { constructor(numColors) { this.numColors = numColors; } get numColors() { return this.numColors; } set numColors(numColors) { this.numColors = numColors; } printNumColors() { console.log(this.numColors); } }
The get and set functions will read and write a class property. Classes contain a constructor method that takes in initialization parameters.
JavaScript classes support inheritance by using the extends keyword as shown below:
CheckerPotholder extends Potholder { constructor(numColors, pattern) { super(numColors); this.pattern = pattern; } printType() { console.log('Checker'); } }
The super keyword is used to pass initialization parameters to the parent class.
Classes are instantiated with the new keyword:
const myPotholder = new CheckerPotholder(2, [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]]);
Static methods can also be created. When I create static methods, I usually put them in their own class.
A static method does something independent of a classes instance variables.
The following is an example:
class SessionStore { static set(key, value) { if (typeof(Storage) !== "undefined") { // Store let seen = []; sessionStorage.setItem(key, JSON.stringify(value, function(key, val) { if (val !== null && typeof val === "object") { if (seen.indexOf(val) >= 0) { return; } seen.push(val); } return val; })); return true; } return false; } static get(key) { if (typeof(Storage) !== "undefined") { return JSON.parse(sessionStorage.getItem(key)); } return null; } static getAll() { if (typeof(Storage) !== "undefined") { return Object.keys(sessionStorage); } return null; } }
This class can be used without creating a new instance. A method is called by calling ClassName.staticMethodName(),
SessionStore.set('potholder', 'the name');
Implementation:
Lets move the static temperature conversion functions in Weather.js to their own class. Inside modules, create a file called TemperatureConverter.js and add the following:
class TemperatureConverter { static convertKelvinToCelsius(kelvin) { if (typeof kelvin !== 'number') { throw 'Kelvin value is not a number'; } return Math.round(kelvin - 273); } static convertCelsiusToFahrenheit(celsius) { if (typeof celsius !== 'number') { throw 'Celsius value is not a number'; } return Math.round((celsius * (9/5)) + 32); }; static convertFahrenheitToKelvin(fahrenheit) { if (typeof fahrenheit !== 'number') { throw 'Fahrenheit value is not a number'; } return Math.round(((5/9) * (fahrenheit - 32)) + 273); }; } export default TemperatureConverter;
Also remove those functions from Weather.js. Weather.js should contain the following. Note, I also added a function called setWeather, which will be populated in a later post when we get to promises and rest api calls.
class Weather { // Constructor constructor() { }; getLocation() { let url = 'https://ipinfo.io/json'; let options = { mode : 'cors' }; }; getWeather(coordinates) { } } export default Weather;
For completeness, also verify javascript_tutorial.js contains the following:
// JavaScript Tutorial /* * This file will add JavaScript * to a website. */ import TemperatureConverter from "./modules/TemperatureConverter.js"; import Weather from "./modules/Weather.js"; (function() { let doc = document; let defaultLocation = [-86.7816, 36.1627]; // longitude, latitude function setWeather(data) { if (data) { let temp = Math.round(data.main.temp); try { let fahrenheit = TemperatureConverter.convertCelsiusToFahrenheit(temp - 273); console.log("Fahrenheit temperature: " + fahrenheit); } catch (error) { console.log("Error setting weather: " + error.message); } } } function init() { let locationStr = ""; for (let i = 0, num = defaultLocation.length; i < num; i++) { locationStr += defaultLocation[i]; if (i === 0) { locationStr += ", "; } } console.log("Setting weather for location: " + locationStr); setWeather({ main: { temp: 30 } }); } init(); })();
Also verify index.html contains the following:
<html> <head> <link rel="stylesheet" href="css/style.css"/> </head> <body> <header> <nav> </nav> <article id="toolbar"> <article id="currentWeather" class="text-center"> <section id="location"> </section> <section id="weatherTemperature"> <span id="temperatureValue"></span> <span id="degreeSymbol">°</span> <span id="temperatureUnits"></span> </section> <section id="weatherDescription"> </section> <img id="weatherIcon"> </img> </article> </article> </header> <main></main> <footer></footer> <script src="js/javascript_tutorial.js" type="module"></script> </body> </html>
You should see the following in the browser console when loading the index.html file:
Setting weather for location: -86.7816, 36.1627
javascript_tutorial.js:19 Fahrenheit temperature: -405
Note, the files will need to be loaded onto a web server. If running them locally in Chrome, you may get a CORS error.
The JavaScript tutorial series starts with this post.
(paid links)
More JavaScript
Leave a Reply
You must be logged in to post a comment.