JavaScript Classes
Last updated: October 15, 2024
Lesson Intro
The newest way to encapsulate code in JavaScript (or just an alternate syntax for the way we already had)
You're on a small screen! Some modules like CodePen examples will behave differently here. You'll need to toggle through their tabs to see all the code. For the best experience, consider using a bigger screen.
object.js
const todoObject = {
todos: [],
count: 0,
add: function(content) {
const todo = {
id: this.count++,
content: content,
};
this.todos.push(todo);
},
listTodos(todos) {
this.todos.forEach( function(todo) {
console.log(todo);
});
},
};
todoObject.add("Go for a run");
todoObject.add("Play tennis");
todoObject.listTodos();
constructor.js
function TodoConstructor() {
this.todos = [];
this.count = 0;
this.add = function(content) {
const todo = {
id: this.count++,
content: content,
};
this.todos = [...this.todos, todo];
};
this.listTodos = function(todos) {
this.todos.forEach( function(todo) {
console.log(todo);
});
};
}
var todoConstructor = new TodoConstructor()
todoConstructor.add("Go for a run");
todoConstructor.add("Play tennis");
todoConstructor.listTodos();
class.js
class TodoClass {
constructor() {
this.todos = [];
this.count = 0;
}
add(content) {
const todo = {
id: this.count++,
content: content,
};
this.todos = [...this.todos, todo];
}
listTodos(todos) {
this.todos.forEach( function(todo) {
console.log(todo);
});
}
}
var todoClass = new TodoClass()
todoClass.add("Go for a run");
todoClass.add("Play tennis");
todoClass.listTodos();
Comparison
See the Pen HTML cheatsheet 1 / display types by perpetual.education (@perpetual-education) on CodePen.
You can use this to add a few features to each and see how the syntax differs.