In JavaScript, the class
keyword is used to define a class, which is a blueprint for creating objects with shared properties and methods. Introduced in ECMAScript 6 (ES6), class
provides a more structured way to work with object-oriented programming (OOP) in JavaScript.
While JavaScript was traditionally prototype-based, the class
syntax was introduced to make the language’s object-oriented capabilities more familiar to developers coming from class-based languages like Java or C++. It’s important to note that the class
keyword is syntactic sugar over JavaScript’s existing prototype-based inheritance.
How the class
Keyword Works in JavaScript
The class
keyword in JavaScript is used to define a class that contains:
- Properties (also known as fields) which hold data related to the object.
- Methods which define the behavior (functions) associated with the class.
Basic Syntax of a Class
class MyClass {
// Constructor function
constructor(name, age) {
this.name = name;
this.age = age;
}
// Method to display name and age
displayInfo() {
console.log(`Name: ${this.name}, Age: ${this.age}`);
}
// Static method (can be called on the class itself, not an instance)
static greet() {
console.log('Hello, welcome to JavaScript classes!');
}
}
Key Components:
- Constructor Method:
- The
constructor
is a special method that is called when an instance of the class is created. It is used to initialize properties of the object. - In the above example, the constructor takes two parameters (
name
,age
) and assigns them to thethis
object, which represents the current instance.
- The
- Instance Method:
displayInfo()
is an instance method that belongs to the class and can be called on objects (instances) created from the class. It accesses and manipulates the instance’s properties.
- Static Method:
greet()
is a static method. Static methods are called on the class itself, not on instances of the class. They do not have access to instance properties or methods, as they are not tied to any particular object.
Creating an Instance of a Class
To create an instance (an object) from a class, you use the new
keyword followed by the class constructor:
const person = new MyClass('Alice', 30);
person.displayInfo(); // Output: Name: Alice, Age: 30
- The
new
keyword creates a new object, initializes it with theconstructor
method, and assigns it to the variableperson
.
Inheritance with Classes
JavaScript classes also support inheritance, allowing you to create a new class based on an existing one. This is done using the extends
keyword.
class Employee extends MyClass {
constructor(name, age, position) {
super(name, age); // Call the parent class constructor
this.position = position;
}
displayInfo() {
super.displayInfo(); // Call the parent class method
console.log(`Position: ${this.position}`);
}
}
const employee = new Employee('Bob', 40, 'Manager');
employee.displayInfo();
// Output:
// Name: Bob, Age: 40
// Position: Manager
- The
Employee
class inherits from theMyClass
class using theextends
keyword. - The
super()
function is used to call the parent class’s constructor and methods.
Getter and Setter Methods in Classes
JavaScript classes also allow the use of getter and setter methods to define how properties are accessed and modified.
class Person {
constructor(name) {
this._name = name; // underscore to indicate it's private
}
// Getter
get name() {
return this._name;
}
// Setter
set name(newName) {
this._name = newName;
}
}
const person = new Person('Alice');
console.log(person.name); // Output: Alice
person.name = 'Bob';
console.log(person.name); // Output: Bob
- Getters allow you to define custom behavior when accessing a property.
- Setters allow you to define custom behavior when assigning a new value to a property.
What’s Happening Behind the Scenes (Prototype-based)
Under the hood, JavaScript still uses prototype-based inheritance, even though class
syntax is used. Every class in JavaScript is essentially a function, and instances of that class have a __proto__
property linking to the class’s prototype.
For example:
console.log(MyClass.prototype); // Shows the prototype of MyClass
In this case, MyClass.prototype
holds the methods and properties that are shared among all instances of MyClass
. The class syntax abstracts away this detail to make the code more readable and easier to maintain.