Class Methods
And instanceof.
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.

- 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.
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);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.
| key | value |
|---|---|
| Methods | the class's behaviour |
| instanceof | made from this class? |
| #field | private data |
| Encapsulation | keep 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