Classes make it easy to create multiple objects that share property names and methods.
To create a new class, we use class
keyword. The class
keyword is followed by a CamelCased class name.
class Person {
// Code
}
An instance is an object that contains the property names and methods of a class, but with unique property values.
For example, to create a person, we use keyword new
const person1 = new Person();
The constructor() method is called when we create a new instance of a class. It sets the property values for each instance.
Remember that a class has only 1 constructor(), writing two constructors() will give a SyntaxError error.
For example, if we want our Person class to have some properties such as firstName, lastName, birthDay, we will put them in the constructor and our properties will be loaded by the constructor first for other methods to use.
class Person {
constructor(firstName, lastName, birthDay) {
this.firstName = firstName;
this.lastName = lastName;
this.birthDay = new Date(birthDay);
}
}
We can add functions in classes easily.
class Person {
constructor(firstName, lastName, birthDay) {
this.firstName = firstName;
this.lastName = lastName;
this.birthDay = new Date(birthDay);
}
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
getBYear() {
return this.birthDay.getFullYear();
}
}
// Object
const p1 = new Person("Anna", "Wood", "3-25-1995");
const p2 = new Person("Joe", "Hopkins", "10-12-1990");
console.log(p2.getFullName()); // Joe Hopkins
console.log(p1.getBYear()); // 1995
Subclass is a class which inherits both the properties and behaviors of the parent’s class.
This prevents code repetition for objects that are similar but need some extra or more specific features.
Subclasses can be created using extends
keyword and super()
.
For example, we can extend Person to the subclass Student.
class Person {
constructor(firstName, lastName, birthDay) {
this.firstName = firstName;
this.lastName = lastName;
this.birthDay = new Date(birthDay);
}
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
getBYear() {
return this.birthDay.getFullYear();
}
}
// Student Subclass
class Student extends Person {
constructor(firstName, lastName, birthDay, school) {
super(firstName, lastName, birthDay);
this.school = school;
}
}
// Instantiate Student
const stu1 = new Student("John", "Smith", "10-3-2008", "junior high school");
console.log(stu1); // Student {firstName: "John", lastName: "Smith", birthDay: Fri Oct 03 2008, school: "junior high school"}
the static
keyword defines a static method for a class.
Static methods are not called on individual instances of the class, but are called on the class itself.
static generatePassword() {
return Math.floor(Math.random() * 10000);