// ES6 Class syntax
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, I'm ${this.name}`;
}
get info() {
return `${this.name}, ${this.age} years old`;
}
static species() {
return 'Homo sapiens';
}
}
const person = new Person('Alice', 30);
console.log(person.greet());
// Inheritance
class Employee extends Person {
constructor(name, age, jobTitle) {
super(name, age);
this.jobTitle = jobTitle;
}
greet() {
return `${super.greet()}, I work as a ${this.jobTitle}`;
}
}
// Private fields
class BankAccount {
#balance = 0;
deposit(amount) {
this.#balance += amount;
return this.#balance;
}
get balance() {
return this.#balance;
}
}
// Prototype-based
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
return `${this.name} makes a sound`;
};
const dog = new Animal('Dog');
console.log(dog.speak());
// Static methods
class MathUtils {
static PI = 3.14159;
static circleArea(radius) {
return this.PI * radius * radius;
}
}
JavaScript classes provide syntactic sugar over prototype-based inheritance using class keyword. I define constructors with constructor() method for initialization. Using extends creates subclasses that inherit from parent classes. The super keyword calls parent class methods and constructors. Instance methods are defined directly in class body. Static methods belong to class itself using static keyword. Private fields use # prefix for encapsulation. Getters and setters with get and set keywords control property access. Understanding prototypes reveals how JavaScript inheritance works under the hood. The prototype chain links objects to their constructors. Modern classes make object-oriented programming more intuitive in JavaScript.