Back to All ArticlesJavaScript Core
JavaScript Core2024-03-181 Min Read663 views
What is class in JavaScript ? How to define and use it?
In JavaScript, a class is a blueprint for creating objects with similar properties and methods. It provides a way to define a particular type of object.
Key Architecture Takeaways
- ES6 classes provide syntactic sugar over JavaScript's prototypal inheritance.
- The constructor method executes automatically when instances are created via new.
- Extend parent functionality cleanly using extends and super() constructor calls.
- Encapsulate shared methods on the prototype to conserve runtime memory.
In JavaScript, a class is a blueprint for creating objects with similar properties and methods. It provides a way to define a particular type of object, encapsulating data for the object and methods to operate on that data. Classes were introduced in ECMAScript 2015 (ES6) to mimic the class-based inheritance found in other object-oriented programming languages.
How to Define a Class
Here's how you define a class in JavaScript:
JAVASCRIPT
class MyClass {
constructor(prop1, prop2) {
this.property1 = prop1;
this.property2 = prop2;
}
method1() {
console.log('Method 1 executing');
}
method2() {
console.log('Method 2 executing');
}
}
```text
In this example:
- `MyClass` is the name of the class.
- `constructor` is a special method for creating and initializing objects created with a class. It is executed automatically when a new object is created with the `new` keyword.
- `method1` and `method2` are methods of the class, defining behaviour for instances of the class.
## Creating an Instance
To create an instance of a class, you use the `new` keyword:
```javascript
const obj = new MyClass('value1', 'value2');
```text
This creates a new object `obj` based on the `MyClass` blueprint, with `property1` set to `'value1'` and `property2` set to `'value2'`.
## Accessing Properties and Methods
You can then access properties and methods of the object using dot notation:
```javascript
console.log(obj.property1); // Output: 'value1'
obj.method1(); // Output: 'Method 1 executing'
```text
## Inheritance
Classes in JavaScript also support inheritance. You can use the `extends` keyword to create a subclass:
```javascript
class SubClass extends MyClass {
constructor(prop1, prop2, prop3) {
super(prop1, prop2);
this.property3 = prop3;
}
method3() {
console.log('Method 3 executing');
}
}
```text
Happy coding!
Found this architecture guide useful?Share this dispatch with your engineering team
Field Engineering Dispatches
Production Runbooks & Architecture Notes
Monthly technical dispatches covering Linux VPS hardening, strict DMARC deliverability, Next.js optimization, and cloud operations. Zero sales fluff.