Class Syntax
ES6 classes provide a cleaner syntax for creating objects and handling inheritance, though they're syntactic sugar over prototypes.
Basic Class
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, I'm ${this.name}`;
}
get info() {
return `${this.name}, age ${this.age}`;
}
}
const alice = new Person('Alice', 30);
console.log(alice.greet()); // 'Hello, I'm Alice'
console.log(alice.info); // 'Alice, age 30'
Class vs Constructor Function
// Constructor function
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
return `${this.name} speaks`;
};
// Class (same thing, cleaner syntax)
class AnimalClass {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} speaks`;
}
}
// Both work the same way
const dog1 = new Animal('Rex');
const dog2 = new AnimalClass('Rex');
console.log(dog1.speak()); // 'Rex speaks'
console.log(dog2.speak()); // 'Rex speaks'
Class is a Function
class MyClass {}
console.log(typeof MyClass); // 'function'
console.log(MyClass.prototype.constructor === MyClass); // true
// Methods are added to prototype
const instance = new MyClass();
console.log(instance.constructor === MyClass); // true
Inheritance
Classes support inheritance using extends and super.
Basic Inheritance
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound`;
}
}
class Dog extends Animal {
bark() {
return `${this.name} barks`;
}
}
const rex = new Dog('Rex');
console.log(rex.speak()); // 'Rex makes a sound' (from Animal)
console.log(rex.bark()); // 'Rex barks' (from Dog)
Using super
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound`;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // Call parent constructor
this.breed = breed;
}
speak() {
return `${super.speak()} and barks`; // Call parent method
}
}
const rex = new Dog('Rex', 'Labrador');
console.log(rex.speak()); // 'Rex makes a sound and barks'
console.log(rex.breed); // 'Labrador'
Method Overriding
class Shape {
constructor(color) {
this.color = color;
}
area() {
return 0; // Base implementation
}
describe() {
return `A ${this.color} shape with area ${this.area()}`;
}
}
class Circle extends Shape {
constructor(color, radius) {
super(color);
this.radius = radius;
}
area() {
return Math.PI * this.radius ** 2;
}
}
const circle = new Circle('red', 5);
console.log(circle.area()); // 78.54
console.log(circle.describe()); // 'A red shape with area 78.54'
Static Methods
Static methods are called on the class itself, not on instances.
Basic Static Methods
class MathHelper {
static add(a, b) {
return a + b;
}
static multiply(a, b) {
return a * b;
}
static PI = 3.14159;
}
// Called on the class, not instances
console.log(MathHelper.add(2, 3)); // 5
console.log(MathHelper.PI); // 3.14159
const helper = new MathHelper();
// helper.add(2, 3); // Error: helper.add is not a function
Static Factory Methods
class User {
constructor(name, email) {
this.name = name;
this.email = email;
}
static fromJSON(json) {
const data = JSON.parse(json);
return new User(data.name, data.email);
}
static create(name, email) {
// Could add validation, logging, etc.
return new User(name, email);
}
}
const user = User.fromJSON('{"name":"Alice","email":"alice@example.com"}');
console.log(user.name); // 'Alice'
Static Properties
class Counter {
static count = 0;
constructor() {
Counter.count++;
}
static getCount() {
return Counter.count;
}
}
new Counter();
new Counter();
console.log(Counter.getCount()); // 2
Private Static Methods (Proposal)
class Database {
static #connection = null;
static #connect() {
// Private static method
return { connected: true };
}
static getConnection() {
if (!this.#connection) {
this.#connection = this.#connect();
}
return this.#connection;
}
}
Getters and Setters
Getters and setters allow you to define property access like syntax for method calls.
Basic Getters and Setters
class Temperature {
constructor(celsius) {
this._celsius = celsius;
}
get fahrenheit() {
return this._celsius * 9/5 + 32;
}
set fahrenheit(f) {
this._celsius = (f - 32) * 5/9;
}
get celsius() {
return this._celsius;
}
set celsius(c) {
if (c < -273.15) {
throw new Error('Temperature below absolute zero');
}
this._celsius = c;
}
}
const temp = new Temperature(100);
console.log(temp.fahrenheit); // 212
console.log(temp.celsius); // 100
temp.fahrenheit = 32;
console.log(temp.celsius); // 0
Computed Properties
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
get area() {
return this.width * this.height;
}
get perimeter() {
return 2 * (this.width + this.height);
}
get isSquare() {
return this.width === this.height;
}
}
const rect = new Rectangle(5, 10);
console.log(rect.area); // 50
console.log(rect.perimeter); // 30
console.log(rect.isSquare); // false
Validation with Setters
class User {
constructor(name, age) {
this.name = name;
this.age = age; // Uses setter
}
get name() {
return this._name;
}
set name(value) {
if (value.length < 2) {
throw new Error('Name must be at least 2 characters');
}
this._name = value;
}
get age() {
return this._age;
}
set age(value) {
if (value < 0 || value > 150) {
throw new Error('Invalid age');
}
this._age = value;
}
}
const user = new User('Alice', 30);
// user.age = -5; // Error: Invalid age
Practice Problems
Create a reusable React component implementing JavaScript Classes. Include proper state management and accessibility.
Solution
// Production-ready component with:
// - Proper TypeScript types
// - Accessibility (ARIA)
// - Error boundaries
// - Loading states
// - Memoization where neededWrite unit and integration tests for JavaScript Classes using React Testing Library.
Solution
// Test coverage:
// 1. Rendering tests
// 2. Interaction tests
// 3. Edge case tests
// 4. Accessibility testsOptimize JavaScript Classes for performance. Consider memoization, code splitting, and bundle size.
Solution
// Optimization techniques:
// 1. React.memo / useMemo / useCallback
// 2. Code splitting with lazy()
// 3. Virtual scrolling for lists
// 4. Image lazy loading
// 5. Bundle analysisQuiz
1. What is a class in JavaScript?
2. What does 'super' do in a class?
3. What is a static method?
4. What is the purpose of getters and setters?
Flashcards
Question
What is a JavaScript class?
Click to reveal answer
Answer
Syntactic sugar over prototype-based inheritance that provides cleaner syntax for creating objects and handling inheritance.
Question
What does extends do?
Click to reveal answer
Answer
Creates a class that inherits from another class, allowing you to use parent methods and properties.
Question
What is a static method?
Click to reveal answer
Answer
A method called on the class itself, not on instances. Useful for utility functions and factory methods.
Question
What are getters and setters?
Click to reveal answer
Answer
Methods that define property access syntax. Getters run when reading, setters when writing.
Question
What is JavaScript Classes?
Click to reveal answer
Answer
JavaScript Classes is a key concept in frontend development.
Revision Notes
Key Takeaways
- 1.Classes are syntactic sugar over prototype-based inheritance
- 2.extends and super enable class inheritance
- 3.Static methods are called on the class itself
- 4.Getters and setters provide property-like access
- 5.Classes make OOP in JavaScript more readable
Interview Tips
- •Explain that classes are syntactic sugar over prototypes
- •Show how to implement inheritance with extends and super
- •Demonstrate static methods and their use cases
- •Explain getters and setters with practical examples
Cheat Sheet
JavaScript Classes Cheat Sheet
Basic Syntax
class MyClass {
constructor() { ... }
method() { ... }
get prop() { ... }
set prop(val) { ... }
static method() { ... }
}
Inheritance
class Child extends Parent {
constructor() {
super();
}
}
Key Points
- Classes are syntactic sugar over prototypes
- super() calls parent constructor
- Static methods called on class, not instances
- Getters/setters use property syntax