AI Hints
JavaScript · Lesson 71 of 138

Class Methods

And instanceof.

⏱ 2 min read▶ Video at 1:26:40🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Methods give a class its behaviour. A well designed class keeps its data and the code that changes it together, so the rest of your program doesn't need to know the details.

Class Methods
From the video: Class Methods
  • Methods give behaviour
  • Data and code together
  • Hide the details

A to-do list class

Our to do list class keeps an array of tasks. Add pushes a task object. Complete marks one as done. And summary returns a line of text. The rest of the program just calls these methods. Instance of checks which class an object came from. Run it.

app.jsjavascript
class TodoList {
  constructor() { this.tasks = []; }
  add(title) { this.tasks.push({ title, done: false }); return this; }
  complete(title) {
    const t = this.tasks.find(t => t.title === title);
    if (t) t.done = true;
  }
  summary() {
    const done = this.tasks.filter(t => t.done).length;
    return `${done} of ${this.tasks.length} done`;
  }
}

const list = new TodoList().add("Shop").add("Cook").add("Clean");
list.complete("Cook");
console.log(list.summary(), list instanceof TodoList);
Output
1 of 3 done true

Private fields

Sometimes you want data that nobody outside the class can touch. Put a hash sign in front of a field's name, like hash balance, and it becomes private. Code outside the class gets an error if it tries to read it. That protects your objects from accidental changes.

keyvalue
Methodsthe class's behaviour
instanceofmade from this class?
#fieldprivate data
Encapsulationkeep details inside

Summary

Methods keep behaviour with the data, instance of checks an object's class, and hash fields are private. Next, building classes on top of other classes.

Key takeaways
  • Methods change the data
  • instanceof
  • #private fields
Next up: Inheritance — extends and super