Chapter 9: Building Larger Structures - Classes, Modules, and APIs
Beyond Simple Functions: Organizing Complex Code
As your JavaScript applications grow in complexity, simply writing functions and variables in a single file becomes unwieldy. Just as Forth allows you to build complex programs from smaller, well-defined "words," JavaScript provides powerful features for organizing your code into reusable and maintainable structures. This chapter will introduce you to Classes, Modules, and APIs, and how to leverage AI to work with them effectively.
Classes: Blueprints for Objects
In object-oriented programming, a class is a blueprint for creating objects (a particular instance of the class). It encapsulates data (properties) and functions (methods) that operate on that data. While JavaScript is primarily a prototype-based language, it offers a class
syntax that makes object-oriented programming more familiar to developers from other languages.
Example 1: Defining a Simple Class
Goal:Define a
Car
class with properties for make
, model
, and year
, and a method to display car information.Prompt:
Define a JavaScript class named Car. The constructor should take make, model, and year as arguments and assign them as properties. Add a method displayInfo that returns a string like "This is a [year] [make] [model]."AI-Generated Code (Expected):
class Car { constructor(make, model, year) { this.make = make; this.model = model; this.year = year; } displayInfo() { return This is a ${this.year} ${this.make} ${this.model}.; } } // Example usage: // const myCar = new Car("Toyota", "Camry", 2020); // console.log(myCar.displayInfo()); // Expected: This is a 2020 Toyota Camry.Analysis: The AI correctly defines a class with a constructor and a method, demonstrating the basic structure of a JavaScript class.
Example 2: Class Inheritance
Classes can inherit properties and methods from other classes, promoting code reuse.
Goal:Create an
ElectricCar
class that inherits from Car
and adds a batteryLife
property.Prompt:
Create a JavaScript class named ElectricCar that extends the Car class.
Its constructor should take make, model, year, and batteryLife
as arguments.
The displayInfo method should be overridden to also include battery life information.
AI-Generated Code (Expected):
class ElectricCar extends Car { constructor(make, model, year, batteryLife) { super(make, model, year); // Call the parent Car constructor this.batteryLife = batteryLife; } displayInfo() { return ${super.displayInfo()} It has a battery life of ${this.batteryLife} kWh.; } } // Example usage: // const tesla = new ElectricCar("Tesla", "Model 3", 2023, 75); // console.log(tesla.displayInfo()); // Expected: This is a 2023 Tesla Model 3. It has a battery life of 75 kWh.Analysis: The AI demonstrates class inheritance using
extends
and super()
, and method overriding, which are key concepts in object-oriented design.
Modules: Organizing Your Codebase
As your projects grow, you'll want to split your code into separate files (modules) to keep it organized and prevent naming conflicts. JavaScript modules (import
and export
) provide a standardized way to do this.
Example 3: Exporting and Importing Functions
Goal:Create a module that exports a utility function and import it into another file.
Prompt:
Create two JavaScript files. File 1 (utils.js): Export a function named capitalize that takes a string and returns it with the first letter capitalized. File 2 (main.js): Import the capitalize function from utils.js and use it to capitalize the string "hello world", then print the result to the console.AI-Generated Code (Expected):
utils.js
:
export function capitalize(str) { if (!str) return ""; return str.charAt(0).toUpperCase() + str.slice(1); }
main.js
:
import { capitalize } from './utils.js'; const message = "hello world"; const capitalizedMessage = capitalize(message); console.log(capitalizedMessage); // Expected: Hello world>Analysis: The AI correctly uses
export
in utils.js
and import
in main.js
, demonstrating how to modularize code. It also includes basic input validation in the capitalize
function.
APIs: Interacting with External Services
An API (Application Programming Interface) is a set of rules and definitions that allows different software applications to communicate with each other. In web development, you'll frequently interact with web APIs to fetch data from servers (e.g., weather data, stock prices, social media feeds) or send data to them.
JavaScript provides the fetch
API for making network requests.
Example 4: Fetching Data from a Public API
Goal:Fetch a random joke from a public API and display it.
Prompt:
Write a JavaScript function fetchRandomJoke that fetches a random joke from the JokeAPI (https://v2.jokeapi.dev/joke/Any?safe-mode). The function should return the joke text (either joke or setup + delivery). Handle potential errors during the fetch operation.AI-Generated Code (Expected):
async function fetchRandomJoke() { try { const response = await fetch("https://v2.jokeapi.dev/joke/Any?safe-mode"); if (!response.ok) { throw new Error(HTTP error! status: ${response.status}); } const data = await response.json(); if (data.type === "single") { return data.joke; } else if (data.type === "twopart") { return ${data.setup} ... ${data.delivery}; } } catch (error) { console.error("Could not fetch joke:", error); return "Failed to fetch a joke. Please try again later."; } } // Example usage (in an async context): // (async () => { // const joke = await fetchRandomJoke(); // console.log(joke); // })();Analysis: The AI correctly uses the
fetch
API with async/await
for asynchronous operations, parses JSON data, and handles different joke types (single vs. two-part). Crucially, it includes error handling, which is vital for robust API interactions.
Conclusion: Building Scalable Applications
Classes, Modules, and APIs are essential tools for building larger, more organized, and interconnected JavaScript applications. By mastering how to prompt AI to generate and work with these structures, you can tackle more ambitious projects and integrate your code with external services. In the next chapter, we will bring all these concepts together to build a complete, real-world application.
---
References:- MDN Web Docs: Classes
- MDN Web Docs: JavaScript modules
- MDN Web Docs: Using the Fetch API
- JokeAPI Documentation
