Aggregation using Object Properties
- Create an object that contains properties representing the components you want to aggregate.
- These properties can be references to other objects, functions, or any data type.
- Establish an aggregation relationship by including one object within the other as a property.
- Allow one object to reference and use another, providing a way to model aggregation.
Example: In this example, we showcase aggregation in JavaScript with two book objects, book1
and book2
, aggregated within a library object, GFG
. The library object has methods to add books dynamically and display their information. A third book, book3
, is added to the library, and the display method is used to show details of all the books in the library.
Javascript
const book1 = { title: "The Great Gatsby" , author: "F.Scott Fitzgerald" }; const book2 = { title: "The w3wiki" , author: "Geek" }; // Create an object representing a library that // aggregates books const GFG = { name: "My Library" , books: [book1, book2], addBook: function (book) { this .books.push(book); }, displayBooks: function () { console.log(`Books in ${ this .name}:`); this .books.forEach((book, index) => { console.log( `${index + 1}. Title: ${book.title}, Author: ${book.author}`); }); } }; // Add more books const book3 = { title: "2023" , author: "George Orwell" }; GFG.addBook(book3); // Display the books GFG.displayBooks(); |
Books in My Library: 1. Title: The Great Gatsby, Author: F.Scott Fitzgerald 2. Title: The w3wiki, Author: Geek 3. Title: 2023, Author: George Orwell
Aggregation in JavaScript
Aggregation is a fundamental concept in object-oriented programming that facilitates the creation of complex objects by combining simpler ones. It establishes a “has-a” relationship between objects, where one object contains references to other objects as its components. This relationship enhances code reusability and modularity in JavaScript applications.
Table of Content
- Aggregation using Object Properties
- Aggregation using Arrays