Classes (ES6)¶
Object-Oriented Programming (OOP)¶
OOP is a programming paradigm based on the concept of "objects", which can contain data and code.
Key Concepts¶
- Class: A blueprint or template for creating objects. (e.g., The blueprint for a Car).
- Object: An instance of a class. (e.g., Your specific red Toyota is an object of the Car class).
- Encapsulation: Hiding the internal details of how an object works and only showing what is necessary. (e.g., You press the gas pedal, you don't need to know how the fuel injection works).
- Inheritance: Creating a new class based on an existing one. (e.g., An "Electric Car" inherits features from a "Car").
- Polymorphism: The ability of different objects to respond to the same command in their own way. (e.g., Both a "Car" and a "Bicycle" have a
move()method, but they move differently). - Abstraction: Focusing on what an object does instead of how it does it. (e.g., Using a TV remote without knowing the electronics inside).
Logic First
OOP helps us model the real world in code. It makes large programs easier to maintain, reuse, and scale.
Class Syntax¶
Use the keyword class to create a class. Always add a method named constructor():
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
age() {
let date = new Date();
return date.getFullYear() - this.year;
}
}
Using the Class¶
Inheritance¶
To create a class inheritance, use the extends keyword.
class Model extends Car {
constructor(name, mod) {
super(name); // Call parent constructor
this.model = mod;
}
show() {
return this.present() + ', it is a ' + this.model;
}
}
Syntactic Sugar
JavaScript classes are Syntactic Sugar over the existing prototype-based inheritance. It doesn't introduce a new object-oriented inheritance model to JavaScript.