Home >Web Front-end >JS Tutorial >My React Journey: Day 15
Object Oriented Programming (OOP)
Object-oriented programming is a programming paradigm based on the concept of objects.
Key Principles of OOP
1.Encapsulation:
function Circle(radius) { this.radius = radius; this.draw = function() { console.log('draw'); }; } const circle = new Circle(5); console.log(circle.radius); // Access encapsulated property circle.draw(); // Call encapsulated method
2.Abstraction:
Hides the details and complexity, exposing only necessary parts of an object.
Simplifies the interface and reduces the impact of changes in the underlying code.
Example: Abstracting methods while hiding internal logic.
3.Inheritance:
Allows a class (child) to inherit properties and methods from another class (parent).
Reduces redundant code.
Example:
class Animal { eat() { console.log("This animal is eating."); } } class Dog extends Animal { bark() { console.log("The dog is barking."); } } const dog = new Dog(); dog.eat(); // Inherited from Animal dog.bark();
4.Polymorphism:
Refers to objects taking many forms.
Allows a unified interface for different object types, enabling code reuse and flexibility.
Example:
class Animal { sound() { console.log("This animal makes a sound."); } } class Dog extends Animal { sound() { console.log("The dog barks."); } } const animal = new Animal(); const dog = new Dog(); animal.sound(); // Output: This animal makes a sound. dog.sound(); // Output: The dog barks.
Importance of OOP
Practical Examples
Classes and Constructors
class Product { constructor(name, price) { this.name = name; this.price = price; } displayProduct() { console.log(`Product: ${this.name}`); console.log(`Price: $${this.price.toFixed(2)}`); } calculateTotal(salesTax) { return this.price + this.price * salesTax; } } const product1 = new Product("Laptop", 1200); product1.displayProduct(); console.log(`Total Price: $${product1.calculateTotal(0.1).toFixed(2)}`);
Inheritance with Animals
class Animal { eat() { console.log("This animal eats food."); } } class Bird extends Animal { fly() { console.log("This bird can fly."); } } const bird = new Bird(); bird.eat(); bird.fly();
Reflection
What I Learned:
OOP is another level.
We go again tomorrow!
The above is the detailed content of My React Journey: Day 15. For more information, please follow other related articles on the PHP Chinese website!