Methods
A class is more than a property container. Methods let you attach behavior — functions that operate on the instance’s own data. Every instance created from the class gets access to all its methods.
Defining methods
Section titled “Defining methods”Methods are defined directly inside the class body, after the constructor:
class Expense { constructor({ id, description, amount, category, date }) { this.id = id ?? crypto.randomUUID(); this.description = description.trim(); this.amount = amount; this.category = category ?? 'Uncategorized'; this.date = date ?? new Date().toISOString().split('T')[0]; }
format() { return `${this.description}: $${this.amount.toFixed(2)}`; }
isInCategory(category) { return this.category.toLowerCase() === category.toLowerCase(); }}
const coffee = new Expense({ description: 'Coffee', amount: 4.50, category: 'Food' });
console.log(coffee.format()); // 'Coffee: $4.50'console.log(coffee.isInCategory('food')); // trueMethods use this to access the instance’s properties. When you call coffee.format(), this inside format is coffee.
Methods are shared, not copied
Section titled “Methods are shared, not copied”This is important: methods are not copied to each instance. They live on the class’s prototype and are shared by all instances. This is efficient — if you create a thousand Expense instances, there is still only one copy of format in memory.
const expense1 = new Expense({ description: 'Coffee', amount: 4.50, category: 'Food' });const expense2 = new Expense({ description: 'Lunch', amount: 12.75, category: 'Food' });
console.log(expense1.format === expense2.format); // true — same functionUseful Expense methods
Section titled “Useful Expense methods”Here are the methods you will add to the Expense class in BudgetBuddy:
class Expense { constructor({ id, description, amount, category, date }) { this.id = id ?? crypto.randomUUID(); this.description = description.trim(); this.amount = amount; this.category = category ?? 'Uncategorized'; this.date = date ?? new Date().toISOString().split('T')[0]; this.createdAt = Date.now(); }
// Returns a human-readable string format() { return `${this.description}: $${this.amount.toFixed(2)}`; }
// Checks category (case-insensitive) isInCategory(category) { return this.category.toLowerCase() === category.toLowerCase(); }
// Returns a plain object suitable for JSON serialization / localStorage toJSON() { return { id: this.id, description: this.description, amount: this.amount, category: this.category, date: this.date, createdAt: this.createdAt, }; }
// Creates an Expense instance from a stored plain object static fromJSON(data) { return new Expense(data); }}toJSON and fromJSON are the bridge between your class instances and localStorage — you will use them heavily in Module 07.
Static methods
Section titled “Static methods”A static method belongs to the class itself, not to any instance. You call it on the class name, not on an instance:
Expense.fromJSON({ id: 'abc', description: 'Coffee', amount: 4.50, category: 'Food', date: '2024-01-15' });fromJSON is a factory method — a static method that constructs and returns a new instance. It is a common pattern for creating instances from different data sources (a JSON file, an API response, localStorage).
You cannot call coffee.fromJSON(...) — fromJSON does not exist on instances, only on the class.
The toString method
Section titled “The toString method”If you define a method named toString, JavaScript calls it automatically when coercing your object to a string:
class Expense { // ... toString() { return `[Expense] ${this.description} $${this.amount.toFixed(2)} (${this.category})`; }}
const coffee = new Expense({ description: 'Coffee', amount: 4.50, category: 'Food' });console.log(`My expense: ${coffee}`);// 'My expense: [Expense] Coffee $4.50 (Food)'Exercise
Section titled “Exercise”Add to your Expense class from the previous lesson:
- A
format()method that returns'Description: $amount'with two decimal places. - An
isInCategory(category)method that returnstrueif the category matches (case-insensitive). - A
toJSON()method that returns a plain object with all properties. - A static
fromJSON(data)method that returns a newExpenseinstance from a plain object. - Create two instances, call
format()on each, and useisInCategoryto test matching and non-matching categories. - Call
toJSON()on one instance, then pass the result toExpense.fromJSON()— confirm the round-trip produces a valid instance.
- Methods are defined inside the class body and access the instance’s data through
this. - Methods live on the prototype — they are shared across all instances, not copied to each one.
staticmethods belong to the class, not to instances — useful for factory patterns and utility functions.toJSON/fromJSONis the standard round-trip pattern for persisting class instances to localStorage or an API.