5 min read
•Question 21 of 50mediumHow do ES6 Classes work in JavaScript?
Understanding class syntax and OOP in JavaScript.
What You'll Learn
- Class syntax
- Inheritance
- Static methods and properties
Basic Class
code.jsJavaScript
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, I'm ${this.name}`;
}
get birthYear() {
return new Date().getFullYear() - this.age;
}
set birthYear(year) {
this.age = new Date().getFullYear() - year;
}
}
const john = new Person('John', 30);
john.greet(); // "Hello, I'm John"Inheritance
code.jsJavaScript
class Employee extends Person {
constructor(name, age, position) {
super(name, age); // Call parent constructor
this.position = position;
}
greet() {
return `${super.greet()}, I'm a ${this.position}`;
}
}
const jane = new Employee('Jane', 25, 'Developer');
jane.greet(); // "Hello, I'm Jane, I'm a Developer"Static Members
code.jsJavaScript
class MathUtils {
static PI = 3.14159;
static add(a, b) {
return a + b;
}
}
MathUtils.PI; // 3.14159
MathUtils.add(1, 2); // 3Private Fields (ES2022)
code.jsJavaScript
class BankAccount {
#balance = 0; // Private field
deposit(amount) {
this.#balance += amount;
}
getBalance() {
return this.#balance;
}
}