Introduction to Constructor Functions in JavaScript
Introduction to Constructor Functions in JavaScript
Before the introduction of ES6 classes, constructor functions were the primary way to create objects and implement inheritance in JavaScript. They remain a fundamental concept for understanding prototype-based inheritance.
In this example, we'll create a Node.js program that illustrates the use of constructor functions and prototype inheritance.
The vertical for this example will be a simple system to manage a library of books and authors.
Step-by-Step Program
1. **Set up Node.js and Visual Studio Code**:
- Make sure Node.js is installed on your system.
- Open Visual Studio Code and create a new directory for your project.
2. **Initialize the Project**:
mkdir library-system
cd library-system
npm init -y
code .
```
3. **Create the JavaScript Files**:
- Create a file named `library.js`.
### `library.js`
```javascript
// Constructor function for Author
function Author(name, birthYear) {
this.name = name;
this.birthYear = birthYear;
}
// Add a method to the Author prototype
Author.prototype.getBio = function() {
return `${this.name} was born in ${this.birthYear}.`;
};
// Constructor function for Book
function Book(title, author, publicationYear) {
this.title = title;
this.author = author; // author should be an instance of Author
this.publicationYear = publicationYear;
}
// Add a method to the Book prototype
Book.prototype.getSummary = function() {
return `${this.title}, written by ${this.author.name}, was published in ${this.publicationYear}.`;
};
// Create instances of Author
const author1 = new Author("J.K. Rowling", 1965);
const author2 = new Author("George Orwell", 1903);
// Create instances of Book
const book1 = new Book("Harry Potter and the Philosopher's Stone", author1, 1997);
const book2 = new Book("1984", author2, 1949);
// Use the methods
console.log(author1.getBio()); // J.K. Rowling was born in 1965.
console.log(author2.getBio()); // George Orwell was born in 1903.
console.log(book1.getSummary()); // Harry Potter and the Philosopher's Stone, written by J.K. Rowling, was published in 1997.
console.log(book2.getSummary()); // 1984, written by George Orwell, was published in 1949.
```
### Explanation
1. **Author Constructor Function**:
- Defines an `Author` with `name` and `birthYear` properties.
- Adds a `getBio` method to the `Author` prototype to get a short biography.
```javascript
function Author(name, birthYear) {
this.name = name;
this.birthYear = birthYear;
}
Author.prototype.getBio = function() {
return `${this.name} was born in ${this.birthYear}.`;
};
```
2. **Book Constructor Function**:
- Defines a `Book` with `title`, `author`, and `publicationYear` properties.
- Adds a `getSummary` method to the `Book` prototype to get a short summary of the book.
```javascript
function Book(title, author, publicationYear) {
this.title = title;
this.author = author; // author should be an instance of Author
this.publicationYear = publicationYear;
}
Book.prototype.getSummary = function() {
return `${this.title}, written by ${this.author.name}, was published in ${this.publicationYear}.`;
};
```
3. **Creating Instances and Using Methods**:
- Instances of `Author` and `Book` are created.
- The methods `getBio` and `getSummary` are called on these instances to demonstrate the functionality.
```javascript
const author1 = new Author("J.K. Rowling", 1965);
const author2 = new Author("George Orwell", 1903);
const book1 = new Book("Harry Potter and the Philosopher's Stone", author1, 1997);
const book2 = new Book("1984", author2, 1949);
console.log(author1.getBio()); // J.K. Rowling was born in 1965.
console.log(author2.getBio()); // George Orwell was born in 1903.
console.log(book1.getSummary()); // Harry Potter and the Philosopher's Stone, written by J.K. Rowling, was published in 1997.
console.log(book2.getSummary()); // 1984, written by George Orwell, was published in 1949.
```
### Running the Program
1. **Install Node.js**: Ensure Node.js is installed on your system. You can download it from [nodejs.org](https://nodejs.org/).
2. **Execute the Script**: Open a terminal in the project directory and run:
```sh
node library.js
```
### Output
The output will be:
```
J.K. Rowling was born in 1965.
George Orwell was born in 1903.
Harry Potter and the Philosopher's Stone, written by J.K. Rowling, was published in 1997.
1984, written by George Orwell, was published in 1949.
```
### Conclusion
This example demonstrates the use of constructor functions and prototype-based inheritance in JavaScript. By encapsulating data and behavior in constructors and prototypes, you can create complex objects and ensure code reusability and maintainability. This approach is fundamental to understanding JavaScript's object-oriented programming capabilities, even as ES6 classes provide a more modern syntax for similar patterns.
Want to print your doc? This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (