JavaScript Classes
Learn to create object blueprints with classes.
1. Defining a Class
Classes are a template for creating objects. They encapsulate data with code to work on that data.
JavaScript Code
Live JavaScript representation with highlighted changes
class Color {constructor(r, g, b) {this.values = [r, g, b];}getRed() {return this.values[0];}}const red = new Color(255, 0, 0);console.log(red.getRed());
2. Inheritance with `extends`
Classes can inherit from other classes using the extends
keyword. This allows you to create a new class that is a modified version of an existing class.
JavaScript Code
Live JavaScript representation with highlighted changes
class Color {constructor(r, g, b) { this.values = [r, g, b]; }toString() { return this.values.join(', '); }}class ColorWithAlpha extends Color {#alpha;constructor(r, g, b, a) {super(r, g, b);this.#alpha = a;}toString() {return `${super.toString()}, ${this.#alpha}`;}}const color = new ColorWithAlpha(255, 0, 0, 0.5);console.log(color.toString());
Console Output