TOOGLE
Javascript classes
-
Front-End
In JavaScript, classes are a syntactical construct introduced in ECMAScript 2015 (ES6) that provide a way to define blueprints for creating objects. They serve as templates for creating objects with shared properties and behaviors. A class in JavaScript defines the structure and behavior of objects using a concise and more familiar syntax compared to traditional constructor functions. It encapsulates data (properties) and functionality (methods) into a single unit, making it easier to organize and maintain code. Here's a basic example of a class in JavaScript.
class Person {
constructor(name, age) {
this._name = name;
this._age = age;
}
// Setter for name
set name(string) {
this._name = string;
}
// Setter for age
set age(number) {
this._age = number;
}
// Getter for name
get name() {
return this._name;
}
// Getter for age
get age() {
return this._age;
}
// Private method to capitalize a string
_capitalize(string) {
return `${string.charAt(0).toUpperCase()}${string.slice(1)}`;
}
// Method to perform a walk action
walk() {
return `${this._name} está andando.`;
}
// Method to increment the age by a given value
incrementAge(value) {
this._age += value;
}
// Method to check if the person is an adult
isAdult() {
return this._age >= 18;
}
// Static method to create a Person instance from an object
static fromObject(obj) {
return new Person(obj.name, obj.age);
}
// Static method to compare two Person instances by age
static compareByAge(person1, person2) {
return person1.age - person2.age;
}
// Method to convert the person's data to a formatted string
toString() {
return `Name: ${this._name}, Age: ${this._age}`;
}
// Method to reset the person's data
reset() {
this._name = '';
this._age = 0;
}
}
// Creating a new Person instance
var person1 = new Person('John', 10);
// Accessing name and age using getters
console.log(person1.name);
console.log(person1.age);
// Modifying name and age using setters
person1.name = 'Mario';
person1.age = 6;
// Accessing updated name and age using getters
console.log(person1.name);
console.log(person1.age);
// Calling the walk() method
console.log(person1.walk());
// Incrementing the age by 5
person1.incrementAge(5);
console.log(person1.age); // Output: 11
// Checking if the person is an adult
console.log(person1.isAdult()); // Output: false
// Creating a new Person instance from an object
var person2 = Person.fromObject({ name: 'Alice', age: 25 });
// Comparing two Person instances by age
console.log(Person.compareByAge(person1, person2)); // Output: -14 (person1 is younger)
// Converting the person's data to a formatted string
console.log(person1.toString()); // Output: "Name: Mario, Age: 11"
// Resetting the person's data
person1.reset();
console.log(person1.name); // Output: ''
console.log(person1.age); // Output: 0