JavaScript: JavaScript Classes and Modules
Last updated: 2026-10-13
As projects grow, you need more than scattered functions and variables — you need organized code structure. Classes provide object-oriented patterns, and Modules provide file-level code isolation. Together, they form the foundation of modern JS projects.
1. Class Syntax
A Class is a template for creating objects — syntactic sugar over constructor functions.
<script>
class ClassName {
constructor(params) {
this.property = params;
}
method() {
// ...
}
}
</script>
▶ Example: Creating a Student Class
▶ Try it Yourselfclass is essentially syntactic sugar over constructor functions + prototypes. new Student() works the same as the old new function Student(), but the syntax is cleaner and more intuitive.
2. Properties and Methods
(1) Instance Properties and Methods
Properties and methods defined with this.xxx inside constructor belong to the instance — each object gets its own copy.
(2) Static Methods
Methods defined with the static keyword belong to the class itself, not to instances. Call them via ClassName.method().
(3) Getters and Setters
Use get and set keywords to define "virtual properties" — functions that execute automatically on read/write.
<div id="output" style="white-space: pre; font-family: monospace; padding: 10px; border: 1px solid #ccc;"></div>
<script>
const output = document.getElementById('output');
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
get fullName() {
return this.firstName + ' ' + this.lastName;
}
set fullName(value) {
const parts = value.split(' ');
this.firstName = parts[0];
this.lastName = parts[1];
}
}
const p = new Person('John', 'Doe');
output.textContent = 'fullName: ' + p.fullName + '\n';
p.fullName = 'Jane Smith';
output.textContent += 'After change: ' + p.fullName;
</script>
▶ Example: Static Methods and Getters/Setters
▶ Try it Yourself3. Inheritance
extends lets a child class inherit properties and methods from a parent class. super calls the parent's constructor or methods.
▶ Example: Inheritance Demo
▶ Try it Yourselfconstructor, you must call super() before using this — because until the parent is initialized, the child's this doesn't exist. This is the easiest rule to forget when learning inheritance.
4. ES Modules
Modules are JS's code organization unit. One module = one file. Variables inside a module are private by default — only explicitly exported items are accessible externally.
(1) Named Exports / Imports
<script>
// math.js
export const PI = 3.14;
export function add(a, b) { return a + b; }
// app.js
import { PI, add } from './math.js';
</script>
(2) Default Exports / Imports
<script>
// logger.js
export default function log(msg) { console.log(msg); }
// app.js
import log from './logger.js';
</script>
(3) Using Modules in HTML
Simply add type="module" to the script tag.
<script type="module">
import { add } from './math.js';
console.log(add(1, 2));
</script>
▶ Example: Single-File Module Simulation (Inline Module)
In real projects, modules should be split into separate files. Here we simulate them within a single HTML file using type="module".
❓ FAQ
new (can't run as plain functions), methods are non-enumerable, and strict mode is on by default. The syntax is cleaner, so Classes are recommended.import and require?import is ES module syntax — statically analyzed at compile time. require is CommonJS (Node.js) — dynamically loaded at runtime. Browsers natively support only ES modules. import must be at the top level; require can be anywhere.export default App; export const utils = {};. Import with: import App, { utils } from './module.js'.📖 Summary
classis syntactic sugar over constructors;constructoris the initializer, and methods are defined on the prototypestaticmethods belong to the class, not instances — ideal for utility and factory methodsget/setdefine virtual properties that intercept reads/writes for validation or computationextendsenables inheritance; a childconstructormust callsuper()first- ES modules use
export/importfor code isolation and reuse;type="module"enables them in HTML - Modules organize code by feature, enable lazy loading, and prevent global namespace pollution
📝 Exercises
- Basic: Create a
Rectangleclass withwidthandheightproperties, plusgetArea()andgetPerimeter()methods. - Intermediate: Add a
get area()getter andset area(value)setter toRectangle(setting area adjusts width/height proportionally). Then create aSquaresubclass that extendsRectangle. - Challenge: Design an
EventManagerclass withon(event, callback),off(event, callback), andemit(event, data)methods to simulate a simple event system (hint: use an object mapping events to arrays of callbacks).