- Introduction to Classes
- Class Declaration
- Class Constructor
- Instance Methods
- Static Methods
- Inheritance
- Getters and Setters
- Private Fields and Methods
Classes in JavaScript provide a more structured way to create objects and handle inheritance. With the introduction of ES6, JavaScript introduced class syntax, which is syntactic sugar over the existing prototype-based inheritance.
Classes can be declared using the class keyword.
javascript class Person { constructor(name, age) { this.name = name; this.age = age; }
greet() { console.log(Hello, my name is ${this.name} and I am ${this.age} years old.); } }In the above example, we have declared a class Person with a constructor that takes in two parameters name and age. We have also defined an instance method greet that logs a greeting message to the console.
The constructor method is a special method for creating and initializing an object created with a class. There can only be one constructor method per class.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const person = new Person('Alice', 30);
console.log(person.name); // 'Alice'
console.log(person.age); // 30- We declare a class
Personwith a constructor that takes in two parametersnameandage. - We create an object
personof thePersonclass by calling thenewoperator and passing in thenameandageparameters. - We log the
nameandageproperties of thepersonobject to the console.
Instance methods are methods that are defined on the class prototype and can be called on instances of the class.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
const person = new Person('Alice', 30);
person.greet(); // 'Hello, my name is Alice and I am 30 years old.'- We declare a class
Personwith a constructor that takes in two parametersnameandage. - We define an instance method
greeton thePersonclass that logs a greeting message to the console. - We create an object
personof thePersonclass by calling thenewoperator and passing in thenameandageparameters. - We call the
greetmethod on thepersonobject to log the greeting message to the console.
Static methods are methods that are defined on the class itself and do not have access to the instance.
class MathHelper {
static square(num) {
return num * num;
}
}
console.log(MathHelper.square(5)); // 25- We declare a class
MathHelperwith a static methodsquarethat takes in a parameternumand returns the square of the number. - We call the
squaremethod on theMathHelperclass and pass in the number5.
Inheritance in JavaScript is a mechanism that allows a class to inherit properties and methods from another class.
To extend a class, we use the extends keyword followed by the name of the class we want to extend.
class Student extends Person {
constructor(name, age, grade) {
super(name, age);
this.grade = grade;
}
study() {
console.log(`${this.name} is studying for grade ${this.grade}.`);
}
}
const student = new Student('Bob', 20, 'A');
student.greet(); // 'Hello, my name is Bob and I am 20 years old.'
student.study(); // 'Bob is studying for grade A.'- We declare a class
Studentthat extends thePersonclass. - We define a constructor for the
Studentclass that calls thesupermethod to call theconstructormethod of thePersonclass and passes in thenameandageparameters. - We define an instance method
studyon theStudentclass that logs a message to the console. - We create an object
studentof theStudentclass by calling thenewoperator and passing in thename,age, andgradeparameters. - We call the
greetmethod on thestudentobject to log the greeting message to the console. - We call the
studymethod on thestudentobject to log the study message to the console.
- The
superkeyword is used to call the parent class constructor. - It can only be used inside the constructor of a subclass.
- It can only be called once in the constructor of a subclass.
- It can be used to pass arguments to the parent class constructor.
class Student extends Person {
constructor(name, age, grade) {
super(name, age); // Calls the parent class constructor
this.grade = grade;
}
greet() {
super.greet(); // Calls the parent class greet method
console.log(`I am a student with grade ${this.grade}.`);
}
}
const student = new Student('Bob', 20, 'A');
student.greet();
// 'Hello, my name is Bob and I am 20 years old.'
// 'I am a student with grade A.'In the above example, we have overridden the greet method on the Student class to call the greet method of the Person class using the super keyword. We have also added a new message to the console that includes the student's grade.
- Getters and setters are special methods that allow us to control the access to an object's properties.
- Getters are used to get the value of a property.
Note
Getters and setters allow you to define object properties that are accessed like regular properties but are actually methods.
class Circle {
constructor(radius) {
this._radius = radius;
}
get diameter() {
return this._radius * 2;
}
set diameter(value) {
this._radius = value / 2;
}
}
const circle = new Circle(5);
console.log(circle.diameter); // 10
circle.diameter = 20;
console.log(circle.diameter); // 20
console.log(circle._radius); // 10ES6+ introduced private fields and methods using the # symbol. These are not accessible outside the class.
class Counter {
#count = 0; // Private field
increment() {
this.#count++;
}
getCount() {
return this.#count;
}
}
const counter = new Counter();
counter.increment();
console.log(counter.getCount()); // 1
console.log(counter.#count); // SyntaxError: Private field '#count' must be declared in an enclosing classIn the above example, we have declared a private field #count and a public method increment that increments the count. We have also defined a public method getCount that returns the value of the count.
- We declare a class
Counterwith a private field#countand a public methodincrementthat increments the count. - We define a public method
getCountthat returns the value of the count. - We create an object
counterof theCounterclass by calling thenewoperator. - We call the
incrementmethod on thecounterobject to increment the count. - We call the
getCountmethod on thecounterobject to get the count. - We try to access the private field
#countdirectly and get aSyntaxError.
Tip
Use classes for creating objects with shared behavior. Leverage inheritance to create specialized classes from base classes. Use getters and setters for controlled access to object properties. Use private fields and methods to encapsulate implementation details.
[EOF]