Object Oriented JavaScript
- JavaScript is an object-oriented language, modeling systems as collections of objects with functions and data.
Object Literal Notation
- Object Literal Notation provides a simple way to create objects in JavaScript, defining their properties and methods in a concise syntax. It is a commonly used approach for creating standalone objects.
const person = {
firstName: "John",
lastName: "Doe",
fullName() {
return `${this.firstName} ${this.lastName}`;
}
};
console.log(person.fullName()); // Output: John Doe
personis an object created using Object Literal Notation. It defines properties likefirstNameandlastName, along with a methodfullName()to concatenate them.
The 'Class' Keyword
- The
classkeyword in JavaScript simplifies the creation of multiple objects with shared properties and methods. It promotes code organization and reusability, making it easier to manage and maintain complex codebases.
class Car {
constructor(make, model) {
this.make = make;
this.model = model;
}
displayInfo() {
console.log(`Make: ${this.make}, Model: ${this.model}`);
}
}
const car1 = new Car("Toyota", "Camry");
const car2 = new Car("Ford", "Mustang");
car1.displayInfo(); // Output: Make: Toyota, Model: Camry
car2.displayInfo(); // Output: Make: Ford, Model: Mustang
Caris a class created using theclasskeyword. It defines a constructor and a method to display car information, promoting code organization and reusability.
Private Methods / Properties
- Private properties and methods in JavaScript can be marked with a
#symbol, ensuring encapsulation and preventing direct access. This helps maintain data integrity and reduces potential conflicts with other parts of the code.
class Person {
#name;
constructor(name) {
this.#name = name;
}
getName() {
return this.#name;
}
}
const person = new Person("John");
console.log(person.getName()); // Output: John
console.log(person.#name); // Error: Private field '#name' must be declared in an enclosing class
#nameis a private property in thePersonclass. It cannot be accessed directly from outside the class, ensuring data privacy and integrity.
Getters / Setters
- Getters and setters provide a way to control the access and manipulation of object properties. This allows for additional logic to be implemented when setting or getting values, such as validation or formatting.
class Temperature {
#celsius;
constructor(celsius) {
this.#celsius = celsius;
}
get fahrenheit() {
return (this.#celsius * 9/5) + 32;
}
set fahrenheit(value) {
this.#celsius = (value - 32) * 5/9;
}
}
const temp = new Temperature(25);
console.log(temp.fahrenheit); // Output: 77
temp.fahrenheit = 32;
console.log(temp.fahrenheit); // Output: 89.6
fahrenheitis a getter/setter property in theTemperatureclass. It converts temperature values between Celsius and Fahrenheit, providing controlled access to temperature data.
Understanding "this"
- Proper understanding and usage of the "this" keyword is essential in object-oriented JavaScript. It refers to the current execution context and allows for accessing the correct object properties within methods.
class Counter {
constructor() {
this.count = 0;
}
increment() {
this.count++;
}
getCount() {
return this.count;
}
}
const counter = new Counter();
counter.increment();
console.log(counter.getCount()); // Output: 1The
increment()method increases thecountproperty of theCounterclass. Thethiskeyword ensures thatcountrefers to the property of the currentCounterinstance.
Inheritance
- Inheritance in JavaScript is achieved through the
extendkeyword, creating a prototype chain between classes. This allows for the reuse of code and the creation of hierarchies of related objects.
class Animal {
speak() {
console.log("Animal makes a sound");
}
}
class Dog extends Animal {
speak() {
console.log("Dog barks");
}
}
const dog = new Dog();
dog.speak(); // Output: Dog barksThe
Dogclass inherits thespeak()method from theAnimalclass. This enables instances ofDogto use thespeak()method, promoting code reuse and hierarchy.
Encapsulation and data hiding
- Encapsulation and data hiding are important concepts in object-oriented programming. By marking properties and methods as private, developers can control access and prevent unintended modifications, enhancing code security and maintainability.
class BankAccount {
#balance;
constructor(initialBalance) {
this.#balance = initialBalance;
}
deposit(amount) {
this.#balance += amount;
}
withdraw(amount) {
if (amount <= this.#balance) {
this.#balance -= amount;
} else {
console.log("Insufficient funds");
}
}
getBalance() {
return this.#balance;
}
}
const account = new BankAccount(1000);
account.deposit(500);
account.withdraw(200);
console.log(account.getBalance()); // Output: 1300
BankAccountclass encapsulates balance information with#balance. Methods likedeposit()andwithdraw()provide controlled access to modify the balance, ensuring data security and integrity.