Classes in JavaScript are a template for creating objects. They encapsulate data with code to work on that data. Introduced in ECMAScript 2015 (ES6), classes provide a syntax more consistent with other programming languages.
Aspects | Class | Function |
---|---|---|
Declaration | class Example {} | function example() {} |
Instantiation | new Example() | example() |
Property/Method Definition | Inside class body | Inside function body or prototype |
Inheritance | Extends keyword | Prototype chain |
A class is defined using the class
keyword, followed by the name of the class. Here's an example:
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
In this example, Rectangle is a class representing rectangular objects.
The constructor method is a special method for creating and initializing an object created within a class. It can include any number of parameters.
Class methods (like the area method below) can be defined inside the class definition.
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
area() {
return this.height * this.width;
}
}
A class is instantiated (i.e., an object is created from the class) using the new keyword:
let rect = new Rectangle(10, 5);
console.log(rect.area()); // 50
The class syntax in JavaScript is a powerful and flexible tool that brings traditional object-oriented features to JavaScript. It is syntactic sugar over the existing prototypal inheritance and constructor functions, but offers a more straightforward and clear syntax. Understanding and utilizing classes effectively can lead to cleaner, more readable code and can help make JavaScript a more approachable language for developers coming from other object-oriented languages.