Classes
A class in JavaScript provides a cleaner, more intuitive syntax that serves as a template for creating new objects, with related attributes and methods. Objects of the same class can be understood as objects of the same type, with common attributes and methods.
To declare a class, we use the
classkeyword, a name, and {} to enclose the block of all its contents. To create a new object from a class, we use thenewkeyword, the name of the class, and()like calling a function, this is known as instancing an object
class Person {
greet() {
console.log('Hello!!');
}
}
const alan = new Person(); // This is instances as an object of type person
alan.greet();
const laura = new Person(); // This is also an object of type person
laura.greet(); // Can do the same actionsIn classes, there is a special method called a constructor that is called every time an object is instantiated, and helps initialize the attributes of new objects. In the instance of an object, we pass values as parameters to be processed by the constructor
class Person {
constructor(name) { // The constructor receives a parameter
this._name = name; // The this keyword must be used
this._behavior = 50;
}
checkBehavior() {
console.log(this._behavior);
}
}
const alan = new Person('Alan'); // We pass a value to the constructor to be set
alan.checkBehavior();In classes, we create getters and setters to access and manipulate attributes, as well as methods to perform actions. The syntax is the same as an object, but we don't use
,to separate methods
We can also define private attributes with the # character, which cannot be accessed from outside the class
This convention only works since ECMAScript 2020 (ES11)
Inheritance
With inheritance, we can create a parent class (superclass) with properties and methods that multiple child classes (subclasses) share, to reutilize code and create objects that share properties. The child classes inherit the properties and methods from their parent class.
In the declaration of the child class, we use the
extendskeyword and the name of the parent class to specify the inheritance. Then we use thesuper()method in the constructor to pass the arguments to the constructor of the parent class, which will assign all methods and attributes of the parent class. However, child classes can also have properties of their own
Also, static methods can be defined, which can only be accessed by calling the class itself and not through the instantiated objects. We use the
statickeyword to define these methods
Last updated