JavaScript: JavaScript Classes and Modules

🗓 Last updated: 2026-11-30👤 Written by: Blake✓ Reviewed by: Dana🏷 Category: JavaScript Tutorial

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.


Related Statements:class set

1. Class Syntax

A Class is a template for creating objects — syntactic sugar over constructor functions.

HTML
<!-- Script tag -->
<script>
class ClassName {
  constructor(params) {
    this.property = params;
  }
  method() {
    // ...
  }
}
</script>

▶ Example: Creating a Student Class

▶ Try it Yourself
💡 Tip: class 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.

HTML
<!-- Container element -->
<div id="output" style="white-space: pre; font-family: monospace; padding: 10px; border: 1px solid #ccc;"></div>
<!-- Script tag -->
<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 Yourself

3. 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 Yourself
💡 Tip: In a child class constructor, 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

HTML
<!-- Script tag -->
<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

HTML
<!-- Script tag -->
<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.

HTML
<!-- Script tag -->
<script type="module">
  import { add } from './math.js';
  console.log(add(1, 2));
</script>
⚠️ Note: Module files are cached by browsers and subject to the same-origin policy. Opening an HTML file locally may fail to load modules — you need to serve it via an HTTP server.

▶ 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".

▶ Try it Yourself

Related Statements:class set

❓ FAQ

Q What is the difference between a JavaScript class and a plain object?
A A class is a template for creating objects; after instantiating it with new, you get independent objects, while a plain object literal {} is a directly created single piece of data. Classes can define constructors, methods, and inheritance, making them suitable for scenarios that need reuse and encapsulated state.
Q What happens if I forget to write new when using a class?
A It throws TypeError: Class constructor X cannot be invoked without 'new'. A class must be called with new and cannot be executed directly like a normal function; if you really need a function-style call, use a regular constructor or a factory function instead.
Q How do I load a class using ES modules in the browser?
A In HTML, use <script type="module" src="./main.js"></script>, then import the class exported by other modules inside the module file. Note that module scripts are deferred by default and run in strict mode, and local files must be accessed through an HTTP server rather than opened directly by double-clicking.

📖 Summary

📝 Exercises

  1. Basic: Create a Rectangle class with width and height properties, plus getArea() and getPerimeter() methods.
  2. Intermediate: Add a get area() getter and set area(value) setter to Rectangle (setting area adjusts width/height proportionally). Then create a Square subclass that extends Rectangle.
  3. Challenge: Design an EventManager class with on(event, callback), off(event, callback), and emit(event, data) methods to simulate a simple event system (hint: use an object mapping events to arrays of callbacks).
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏