How to use ES6 Classes In Javascript
To create a struct-like object using ES6 classes, you define a class using the class keyword, followed by the class name. Inside the class, you define a constructor method to initialize the object’s properties and methods. After defining, you can create instances of the class using the new keyword. You can access and manipulate the properties of it using dot notation.
Example: Explanation of Structs in JavaScript Using ES6 Classes.
class Person {
constructor(name, age, occupation) {
this.name = name;
this.age = age;
this.occupation = occupation;
}
// Method to display person's details
displayDetails() {
console.log(`Name: ${this.name}, Age: ${this.age},
Occupation: ${this.occupation}`);
}
}
// Creating an instance of Person
const person1 = new Person('John Doe', 30, 'Engineer');
const person2 = new Person('Jane Smith', 25, 'Doctor');
// Accessing properties
console.log("Name:", person1.name);
console.log("Age:", person2.age);
// Updating properties
person1.name = 'Ram';
person2.age = 45;
// Calling method to display details
person1.displayDetails();
person2.displayDetails();
Output
Name: John Doe Age: 25 Name: Ram, Age: 30, Occupation: Engineer Name: Jane Smith, Age: 45, Occupation: Doctor
How to work with Structs in JavaScript ?
Structs are typically found in languages like C, C++, and similar, and they provide a way to organize related data items under one name. Typically JavaScript does not have built-in support for structs, but you can achieve similar functionality using objects. Objects in JavaScript are dynamic collections of key-value pairs, where keys are strings (or Symbols) and values can be any data.
Table of Content
- Using Objects
- Using ES6 Classes
- Using String Split()
- Using the ‘this’ Keyword in Class
- Using the ‘this’ Keyword in Object