Chapter XX · Classes

Class Methods

Class methods are functions defined inside a class body that are automatically added to the instance's prototype.

01 How It Works

Think of built-in control action buttons installed on every device model off an assembly line.

Methods defined in a class are shared across all instances via the prototype, saving memory.

example.js
class Calculator {
  add(a, b) {
    return a + b;
  }
}
const calc = new Calculator();
calc.add(2, 3); // 5
  1. 1. Write method identifiers inside a class body without the `function` keyword.

  2. 2. Access instance state via the `this` keyword.

  3. 3. Invoke methods on class instance objects.

02 Practical Example

Here is how you might see this concept applied in real-world code:

practical.js
class User {
  constructor(name) { this.name = name; }
  greet() { console.log(`Hi ${this.name}`); }
}

Key Takeaway

Class methods provide shared behaviors stored efficiently on the prototype object.

Related Concepts