404 Not Found

404 Not Found


nginx

JavaScript Classes and Modules

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.


Class Syntax

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

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

Example: Creating a Student Class

HTML
<div id="output" style="padding: 10px; border: 1px solid #ccc;"></div>

<script>
const output = document.getElementById('output');

class Student {
  constructor(name, age, grade) {
    this.name = name;
    this.age = age;
    this.grade = grade;
  }

  introduce() {
    return 'My name is ' + this.name + ', I am ' + this.age + ' years old, in grade ' + this.grade + '.';
  }

  study(subject) {
    return this.name + ' is studying ' + subject + '.';
  }
}

const s1 = new Student('Alice', 12, '6th');
const s2 = new Student('Bob', 11, '5th');

output.textContent = s1.introduce() + '\n' + s2.introduce() + '\n' + s1.study('Math');
</script>
▶ Try it Yourself
💡 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.


Properties and Methods

Instance Properties and Methods

Properties and methods defined with this.xxx inside constructor belong to the instance — each object gets its own copy.

Static Methods

Methods defined with the static keyword belong to the class itself, not to instances. Call them via ClassName.method().

Getters and Setters

Use get and set keywords to define "virtual properties" — functions that execute automatically on read/write.

HTML
<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

HTML
<div id="output" style="white-space: pre; font-family: monospace; padding: 10px; border: 1px solid #ccc;"></div>

<script>
const output = document.getElementById('output');

class Circle {
  static count = 0;

  constructor(radius) {
    this.radius = radius;
    Circle.count++;
  }

  get area() {
    return Math.PI * this.radius * this.radius;
  }

  get diameter() {
    return this.radius * 2;
  }

  set diameter(value) {
    this.radius = value / 2;
  }

  static createUnit() {
    return new Circle(1);
  }
}

const c1 = new Circle(5);
const c2 = new Circle(10);
const c3 = Circle.createUnit();

output.textContent = 'Circle with radius 5:\n';
output.textContent += '  Area: ' + c1.area.toFixed(2) + '\n';
output.textContent += '  Diameter: ' + c1.diameter + '\n';
output.textContent += '  Set diameter to 20:\n';
c1.diameter = 20;
output.textContent += '  New radius: ' + c1.radius + '\n\n';
output.textContent += 'Total circles created: ' + Circle.count + '\n';
output.textContent += 'Unit circle radius: ' + c3.radius;
</script>
▶ Try it Yourself

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

HTML
<div id="output" style="white-space: pre; font-family: monospace; padding: 10px; border: 1px solid #ccc;"></div>

<script>
const output = document.getElementById('output');

class Animal {
  constructor(name, sound) {
    this.name = name;
    this.sound = sound;
  }

  speak() {
    return this.name + ' says: ' + this.sound;
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    super(name, 'Woof');
    this.breed = breed;
  }

  fetch(item) {
    return this.name + ' fetched the ' + item;
  }
}

class Cat extends Animal {
  constructor(name, indoor) {
    super(name, 'Meow');
    this.indoor = indoor;
  }

  purr() {
    return this.name + ' is purring...';
  }
}

const dog = new Dog('Rex', 'Shiba Inu');
const cat = new Cat('Whiskers', true);

output.textContent = dog.speak() + '\n';
output.textContent += dog.fetch('frisbee') + '\n';
output.textContent += cat.speak() + '\n';
output.textContent += cat.purr();
</script>
▶ Try it Yourself
💡 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.


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.

Named Exports / Imports

HTML
<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>

Default Exports / Imports

HTML
<script>
// logger.js
export default function log(msg) { console.log(msg); }

// app.js
import log from './logger.js';
</script>

Using Modules in HTML

Simply add type="module" to the script tag.

HTML
<script type="module">
  import { add } from './math.js';
  console.log(add(1, 2));
</script>
⚠️ 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".

HTML
<div id="output" style="padding: 10px; border: 1px solid #ccc;"></div>

<script type="module">
const output = document.getElementById('output');

const calculator = {
  add(a, b) { return a + b; },
  subtract(a, b) { return a - b; },
  multiply(a, b) { return a * b; },
  divide(a, b) { return b !== 0 ? a / b : 'Cannot divide by zero'; }
};

const formatter = {
  currency(value) { return '$' + value.toFixed(2); },
  percent(value) { return (value * 100).toFixed(1) + '%'; }
};

const r1 = calculator.add(10, 20);
const r2 = calculator.multiply(5, 4);
const r3 = calculator.divide(10, 3);

output.textContent = '10 + 20 = ' + r1 + '\n';
output.textContent += '5 × 4 = ' + r2 + '\n';
output.textContent += '10 ÷ 3 = ' + formatter.currency(r3) + '\n';
output.textContent += '0.85 → ' + formatter.percent(0.85);

// In a real project you would split like this:
// calculator.js → export { calculator }
// formatter.js → export { formatter }
// main.js → import { calculator } from './calculator.js'
//           import { formatter } from './formatter.js'
</script>
▶ Try it Yourself

📖 Summary

  1. class is syntactic sugar over constructors; constructor is the initializer, and methods are defined on the prototype
  2. static methods belong to the class, not instances — ideal for utility and factory methods
  3. get/set define virtual properties that intercept reads/writes for validation or computation
  4. extends enables inheritance; a child constructor must call super() first
  5. ES modules use export/import for code isolation and reuse; type="module" enables them in HTML
  6. Modules organize code by feature, enable lazy loading, and prevent global namespace pollution

❓ FAQ

Q: What's the real difference between a Class and a constructor function? A: No fundamental difference — Class is syntactic sugar. But Classes have a few traits: they must be called with 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.

Q: What's the difference between import and require? A: 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.

Q: Can you mix default and named exports? A: Yes. A module can have one default export and multiple named exports: export default App; export const utils = {};. Import with: import App, { utils } from './module.js'.

📝 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).
100%

🙏 帮我们做得更好

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

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