Professional Documents
Culture Documents
It Is JS OOP
It Is JS OOP
In JavaScript, a class is defined using the class keyword followed by the class name. A
class defines the properties and methods that all instances of the class will have.
class Person {
constructor(name) {
this.name = name;
}
introduceSelf() {
console.log(`Hi! My name is ${this.name}`);
}
}
● A constructor method that initializes the name property of the new instance.
● An introduceSelf() method that logs a greeting to the console.
Instances
An instance of a class is an object that has been created from the class blueprint. Instances
have the same properties and methods as defined in the class, but their values can be
different.
This code creates two Person instances: person1 and person2. Both instances have the
name property and the introduceSelf() method. The name property of person1 is set to
'Alice', and the name property of person2 is set to 'Bob'. When calling introduceSelf() on
each instance, the respective name property is used to personalize the greeting.
Inheritance
Inheritance is a mechanism that allows a class to inherit properties and methods from
another class. The subclass, which is the inheriting class, can also define its own properties
and methods.
getCompany() {
return this.company;
}
}
This code defines an Employee class that inherits from the Person class. The Employee
class has its own company property and a getCompany() method. It also calls the
constructor of the Person class to initialize the name property.
This code creates an Employee instance and demonstrates that it can access both inherited
and its own properties and methods.
Encapsulation
Encapsulation is a principle that restricts direct access to an object's internal data and only
allows access through its defined methods. This helps protect the object's state and ensures
that only authorized code can modify it.
class Account {
#balance = 0; // Private property
constructor(initialDeposit) {
this.deposit(initialDeposit);
}
deposit(amount) {
if (amount < 0) {
throw new Error('Invalid deposit amount');
}
this.#balance += amount;
}
getBalance() {
return this.#balance;
}
}
This code defines an Account class with a private #balance property. The private property
can only be accessed directly within the class. The deposit() method provides a controlled
way to modify the #balance property, ensuring that only valid deposits are allowed. The
getBalance() method provides a controlled way to access the #balance property without
allowing direct modification.