Harshil Chovatiya - Day 9: Objects and Object-Oriented Programming in JavaScript
Day 9: Objects and Object-Oriented Programming in JavaScript
Overview:
- Objects are fundamental in JavaScript, allowing you to store and manipulate data in a structured way.
- Object-oriented programming (OOP) principles are widely used for organizing code.
In-Depth:
Creating Objects:
- Objects are created using curly braces `{}` and can contain properties and methods.
var person = {
firstName: "John",
lastName: "Doe",
age: 30,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
Accessing Object Properties:
- Object properties are accessed using dot notation or square brackets.
console.log(person.firstName); // Dot notation
console.log(person["lastName"]); // Square brackets
Adding and Modifying Properties:
- You can add or modify object properties dynamically.
person.email = "john@example.com"; // Add a new property
person.age = 31; // Modify an existing property
Object Methods:
- Objects can contain functions as methods to perform actions.
console.log(person.fullName()); // Invoke a method
Object Constructors:
- Constructors allow you to create multiple objects with the same structure using a blueprint.
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
var myCar = new Car("Toyota", "Camry", 2022);
Prototypes and Inheritance:
- Prototypes enable objects to inherit properties and methods from other objects.
Car.prototype.startEngine = function() {
console.log("Engine started.");
};
myCar.startEngine(); // Output: "Engine started."
Object-Oriented Programming (OOP):
- OOP is a programming paradigm that uses objects and classes to structure code.
- It encourages encapsulation, inheritance, and polymorphism.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + " makes a sound.");
}
}
class Dog extends Animal {
speak() {
console.log(this.name + " barks.");
}
}
Day 9 explores objects and object-oriented programming (OOP) concepts in JavaScript. Objects are a fundamental data structure, and understanding how to create, access, and manipulate them is crucial. Additionally, OOP principles provide a structured way to organize code and promote code reusability and maintainability through encapsulation and inheritance. These concepts are essential for building complex and maintainable JavaScript applications.
Day 10: Revision and Practice
Day 10 is dedicated to revision and practice. It's a time to reinforce the concepts learned in the previous days, including object-oriented programming and working with objects in JavaScript. Use this day to review your code, tackle exercises, and solidify your understanding. Practicing what you've learned is a crucial step in becoming proficient in JavaScript.
Comments
Post a Comment