Object-Oriented Programming
Object-Oriented Programming (OOP) is a paradigm that models real-world entities as objects with properties and methods. Objects in JavaScript can be created using object literals, constructor functions, factory functions, or classes (introduced in ES6).
If you are coming from Java or C++, you know that classes are the main way we organize code in those languages. JavaScript added the class keyword in 2015, in ES6. Here is an example of defining a class and instantiating it in JavaScript.
class Circle {
constructor(radius) {
this.radius = radius;
}
calculateArea() {
return Math.PI * this.radius * this.radius;
}
}
const myCircle = new Circle(5);
console.log(myCircle.calculateArea()); // 78.53981633974483
Most of this chapter is about the class syntax. But we will first look at how JavaScript handled object-oriented patterns before classes existed: methods, execution context, constructor functions, and prototypes. Once you know those, it is easier to see what the class syntax gives you and how it works underneath.
Learning Outcomes
- Explain how JavaScript represented object-oriented patterns before classes, using constructor functions, prototypes, and execution context
- Define classes with the class syntax, including fields, methods, getters and setters, privacy, and static members
- Build class hierarchies with inheritance and polymorphism, and use composition as an alternative
- Apply object-oriented design principles to structure related state and behavior in JavaScript programs