ES6 – Classes
Hi, ES6 introduces a new way (syntax) to declare classes and do not change the object-oriented model existing in JS.
First that all “classes” are functions that are used as constructors, so you can have classes if you want to use it for constructing objects.
The ways to declare classes are 2: class declaration and the other is class expression.
The class declaration way
For this way we need to use the class keyword followed by the class name.
// Class declaration
class myClass {
}
Then we can define the constructor method inside the class:
// Class declaration
class myClass {
// constructor method
constructor(name) {
this.name = name;
}
}
And finally we can create a new instance of our class:
// Class declaration
class myClass {
// constructor method
constructor(name) {
this.name = name;
}
}
// Creating a new instance (object) of the class myClass
let person = new myClass("Cristina Rojas");
console.log("person --->", person);
Result:
Note: see how the prototype object of my new instance (person) is myClass object.
Now, method are functions that will go inside the class but to declare this method we don’t need to use “function” keyword and the comma is not used in between methods.
// Class declaration
class myClass {
// constructor method
constructor(name) {
this.name = name;
}
// method
myFirstMethod() {}
mySecondMethod() {}
}
There can be only one constructor by class, not more and all the code inside the function it will be executed as “strict” mode.
The class expression way
In this way we are able to omit the class name.
// Expression declaration
let Person = class {
constructor(name) {
this.name = name;
}
};
let newPerson = new Person("Cristina Rojas");
console.log("newPerson --->", newPerson);
Result:
By Cristina Rojas.