JavaScript Classes and OOP
# JavaScript Classes and OOP
Up until now, whenever we needed an object, we created it manually using {}. But what if you are building a school management system and you need to create 500 Student objects? Typing out { name: "...", age: ... } 500 times is impossible.
In this chapter, we will learn Object-Oriented Programming (OOP) by creating Classes—blueprints for generating objects automatically.
1. Introduction
A Class is a template for creating objects. It defines the properties and methods that the created objects (called Instances) will have.
Before ES6, JavaScript handled OOP using "Constructor Functions" and the Prototype chain, which was confusing for developers coming from languages like Java or C++. ES6 introduced the class keyword to make OOP in JavaScript cleaner and more intuitive.
2. Learning Objectives
By the end of this chapter, you will be able to:
-
Define a Class using the
classkeyword.
-
Understand and use the
constructor()method.
- Add methods to a Class.
-
Instantiate new objects using the
newkeyword.
-
Understand Inheritance using the
extendsandsuperkeywords.
- Build a Student Management System mini-project.
3. Class Syntax and the Constructor
To create a class, use the class keyword followed by the name of the class (Class names should always start with a Capital Letter).
Inside the class, you MUST add a method named constructor(). This is a special function that runs automatically every time a new object is created from this class. It is used to initialize the object's properties.
4. Creating Instances (The new keyword)
A class does nothing on its own. It is just a blueprint. To actually build an object from it, you must use the new keyword.
---
5. Real-world Examples & Code Snippets
Example 1: Creating a Basic Class
Example 2: Adding Methods to a Class
You can add standard methods inside the class. Notice you do NOT use the function keyword for class methods.
Example 3: Method Chaining
If you return this at the end of a method, you can chain multiple methods together!
Example 4: Inheritance (extends)
Inheritance allows a new class to inherit all the properties and methods of an existing class. It is excellent for code reusability.
Example 5: The super Keyword
If a child class has its own constructor, it MUST call super() before it can use this. super() calls the constructor of the parent class.
Example 6: Static Methods
Static methods are attached to the Class itself, NOT to the individual objects (instances) created from it. They are often used for utility functions.
Example 7: Private Properties (Modern ES2022)
By prefixing a property with #, it becomes completely private and cannot be accessed from outside the class.
---
6. Common Mistakes for Beginners
-
1.
Forgetting
this: Inside a class, if you want to access a property, you MUST usethis.propertyName. If you just writepropertyName, JS will look for a local variable and throw a ReferenceError.
-
2.
Forgetting the
newkeyword: Callingconst c = Car("Ford")withoutnewwill throw a TypeError: Class constructor cannot be invoked without 'new'.
-
3.
Putting commas between methods: In an Object Literal
{}, you separate properties and methods with commas. In a Class{}, there are NO commas between methods.
7. Best Practices
-
Capitalize Class names (
class UserManager) to distinguish them from regular variables and functions.
-
Keep classes focused on a single entity. Don't create a
GodClassthat manages Users, Products, and Database Connections all at once.
8. Mini Project: Student Management System
Let's build a UI that instantiates objects from a Student class and displays them.
HTML:
school.js:
9. Exercises
-
1.
Create a
Bookclass with a constructor that takestitleandauthor.
-
2.
Instantiate two different books using the
newkeyword.
-
3.
Add a method
read()to theBookclass that console logs "You are reading [title]". Call this method on one of your instances.
10. MCQs (Multiple Choice Questions)
Q1: What special method runs automatically when a new class instance is created?
A) init()
B) start()
C) constructor()
D) build()
*Answer: C*
Q2: Which keyword is used to create a child class from a parent class?
A) inherits
B) extends
C) super
D) childOf
*Answer: B*
Q3: Which keyword is required to invoke a class and generate an object?
A) create
B) generate
C) make
D) new
*Answer: D*
11. Interview Questions
Q: Explain the super keyword in JavaScript Classes.
*A: The super keyword is used within a child class to call the constructor or methods of its parent class. If a child class has its own constructor, calling super() is strictly required before the this keyword can be used.*
Q: Are ES6 Classes actually real classes like in Java? *A: No. Under the hood, JavaScript is a "Prototype-based" language. ES6 classes are just "syntactic sugar" over JavaScript's existing prototype-based inheritance. They behave similarly, but the underlying engine implementation is entirely different from classical OOP languages.*
12. FAQs
Q: Do I have to use Classes? *A: No. Many modern developers prefer "Functional Programming" over OOP. For example, React heavily shifted away from Class Components to Functional Components in 2019. However, understanding classes is mandatory for understanding the wider JS ecosystem (like Node.js and Angular).*
13. Summary
- Classes are blueprints for creating Objects.
-
constructor()sets up the object's initial data.
-
The
newkeyword builds the actual object (Instance).
-
extendscreates a child class (Inheritance).
-
super()calls the parent's constructor.
- Static methods belong to the class, not the instances.