JavaScript Classes: Comprehensive Guide
JavaScript Classes: Comprehensive Guide 1
What are Classes in JavaScript? 2
Basic Syntax 2
Example: Define and Instantiate a Class 3
Class Methods and Properties 3
Example: Static Methods 3
Learn more HTML, CSS, JavaScript Web Development at [Link] Laurence Svekis
1
Inheritance with Classes 3
Example: Class Inheritance 3
Private and Public Fields 4
Example: Private Fields 4
Getters and Setters 4
Example: Using Getters and Setters 5
Exercises 5
Exercise 1: Create a Vehicle Class 5
Exercise 2: Implement a Calculator Class 6
Exercise 3: Inheritance 6
Multiple-Choice Questions 7
Question 1: 7
Question 2: 7
Question 3: 7
Best Practices for Using Classes 8
JavaScript Classes provide a way to create reusable object templates using a modern syntax.
This guide covers the basics, advanced features, practical examples, exercises, and
multiple-choice questions to help you master JavaScript classes.
What are Classes in JavaScript?
Classes are syntactic sugar over JavaScript’s prototype-based inheritance model. They allow
you to define object templates with properties and methods.
Basic Syntax
class ClassName {
constructor(param1, param2) {
this.property1 = param1;
this.property2 = param2;
}
method1() {
[Link](this.property1);
}
}
● constructor: A special method for initializing object properties.
● this: Refers to the instance of the class.
Learn more HTML, CSS, JavaScript Web Development at [Link] Laurence Svekis
2
Example: Define and Instantiate a Class
class Person {
constructor(name, age) {
[Link] = name;
[Link] = age;
}
greet() {
[Link](`Hi, my name is ${[Link]} and I'm ${[Link]} years
old.`);
}
}
const person1 = new Person("Alice", 30);
[Link](); // Output: Hi, my name is Alice and I'm 30 years old.
Class Methods and Properties
1. Instance Methods: Methods available on instances of the class.
2. Static Methods: Methods that belong to the class itself, not the instances.
Example: Static Methods
class MathHelper {
static add(a, b) {
return a + b;
}
}
[Link]([Link](5, 3)); // Output: 8
Inheritance with Classes
Classes support inheritance through the extends keyword. The super keyword calls the
parent class's constructor or methods.
Example: Class Inheritance
class Animal {
constructor(name) {
[Link] = name;
}
speak() {
[Link](`${[Link]} makes a noise.`);
Learn more HTML, CSS, JavaScript Web Development at [Link] Laurence Svekis
3
}
}
class Dog extends Animal {
speak() {
[Link]();
[Link](`${[Link]} barks.`);
}
}
const dog = new Dog("Rex");
[Link]();
// Output:
// Rex makes a noise.
// Rex barks.
Private and Public Fields
JavaScript classes can define private and public fields.
Example: Private Fields
class BankAccount {
#balance = 0;
deposit(amount) {
this.#balance += amount;
}
getBalance() {
return this.#balance;
}
}
const account = new BankAccount();
[Link](100);
[Link]([Link]()); // Output: 100
// [Link](account.#balance); // Error: Private field '#balance'
must be declared in an enclosing class
● #balance: Denotes a private field accessible only within the class.
Getters and Setters
Getters and setters are used to define accessors for properties.
Learn more HTML, CSS, JavaScript Web Development at [Link] Laurence Svekis
4
Example: Using Getters and Setters
class Rectangle {
constructor(width, height) {
[Link] = width;
[Link] = height;
}
get area() {
return [Link] * [Link];
}
set dimensions({ width, height }) {
[Link] = width;
[Link] = height;
}
}
const rect = new Rectangle(10, 20);
[Link]([Link]); // Output: 200
[Link] = { width: 5, height: 15 };
[Link]([Link]); // Output: 75
Exercises
Exercise 1: Create a Vehicle Class
1. Create a class Vehicle with properties make and model.
2. Add a method getDetails that prints make and model.
Solution:
class Vehicle {
constructor(make, model) {
[Link] = make;
[Link] = model;
}
getDetails() {
[Link](`Make: ${[Link]}, Model: ${[Link]}`);
}
}
const car = new Vehicle("Toyota", "Corolla");
[Link](); // Output: Make: Toyota, Model: Corolla
Learn more HTML, CSS, JavaScript Web Development at [Link] Laurence Svekis
5
Exercise 2: Implement a Calculator Class
1. Create a class Calculator with static methods add, subtract, multiply, and
divide.
2. Test the methods with sample inputs.
Solution:
class Calculator {
static add(a, b) {
return a + b;
}
static subtract(a, b) {
return a - b;
}
static multiply(a, b) {
return a * b;
}
static divide(a, b) {
return b !== 0 ? a / b : "Cannot divide by zero";
}
}
[Link]([Link](5, 3)); // Output: 8
[Link]([Link](10, 2)); // Output: 5
Exercise 3: Inheritance
1. Create a parent class Employee with properties name and position.
2. Create a child class Manager that inherits from Employee and adds a method
announce.
Solution:
class Employee {
constructor(name, position) {
[Link] = name;
[Link] = position;
}
details() {
[Link](`${[Link]} works as a ${[Link]}`);
Learn more HTML, CSS, JavaScript Web Development at [Link] Laurence Svekis
6
}
}
class Manager extends Employee {
announce() {
[Link](`${[Link]} is a manager!`);
}
}
const manager = new Manager("John", "Manager");
[Link](); // Output: John works as a Manager
[Link](); // Output: John is a manager!
Multiple-Choice Questions
Question 1:
What is the purpose of the constructor in a class?
1. To define class methods.
2. To initialize properties of the class.
3. To extend another class.
4. To create static methods.
Answer: 2. To initialize properties of the class.
Question 2:
Which keyword is used to inherit from another class in JavaScript?
1. implements
2. extends
3. inherits
4. prototype
Answer: 2. extends
Question 3:
How do you define a private field in a JavaScript class?
1. Use the private keyword.
2. Use the # symbol before the field name.
3. Prefix the field name with _.
Learn more HTML, CSS, JavaScript Web Development at [Link] Laurence Svekis
7
4. Declare the field inside a method.
Answer: 2. Use the # symbol before the field name.
Best Practices for Using Classes
1. Encapsulation: Use private fields and methods to hide implementation details.
2. DRY Principle: Use inheritance to avoid duplicate code.
3. Static Methods: Use static methods for utility functions that don't depend on instance
data.
4. Meaningful Names: Use meaningful class and method names for readability.
Learn more HTML, CSS, JavaScript Web Development at [Link] Laurence Svekis