- 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
Person
with a constructor that takes in two parametersname
andage
. - We create an object
person
of thePerson
class by calling thenew
operator and passing in thename
andage
parameters. - We log the
name
andage
properties of theperson
object 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
Person
with a constructor that takes in two parametersname
andage
. - We define an instance method
greet
on thePerson
class that logs a greeting message to the console. - We create an object
person
of thePerson
class by calling thenew
operator and passing in thename
andage
parameters. - We call the
greet
method on theperson
object 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
MathHelper
with a static methodsquare
that takes in a parameternum
and returns the square of the number. - We call the
square
method on theMathHelper
class 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
Student
that extends thePerson
class. - We define a constructor for the
Student
class that calls thesuper
method to call theconstructor
method of thePerson
class and passes in thename
andage
parameters. - We define an instance method
study
on theStudent
class that logs a message to the console. - We create an object
student
of theStudent
class by calling thenew
operator and passing in thename
,age
, andgrade
parameters. - We call the
greet
method on thestudent
object to log the greeting message to the console. - We call the
study
method on thestudent
object to log the study message to the console.
- The
super
keyword 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); // 10
ES6+ 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 class
In 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
Counter
with a private field#count
and a public methodincrement
that increments the count. - We define a public method
getCount
that returns the value of the count. - We create an object
counter
of theCounter
class by calling thenew
operator. - We call the
increment
method on thecounter
object to increment the count. - We call the
getCount
method on thecounter
object to get the count. - We try to access the private field
#count
directly 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]