How to Use JavaScript Prototypes - Practical Examples


JavaScript prototypes are a fundamental concept that allows you to extend and share functionality among objects. They are especially useful for adding methods to constructor functions and creating efficient, reusable code. In this guide, we'll explore practical examples of how to use JavaScript prototypes.


Example 1: Adding Methods to Objects


Prototypes are commonly used to add methods to objects. Here's an example of how to add a greet() method to a Person object:


function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log('Hello, my name is ' + this.name);
}
const person1 = new Person('Alice');
const person2 = new Person('Bob');
person1.greet(); // Outputs: 'Hello, my name is Alice'
person2.greet(); // Outputs: 'Hello, my name is Bob'

Example 2: Inheriting Methods


Prototypes support inheritance. You can create a new object that inherits methods from another object. Here's an example of creating a Student object that inherits the greet() method from the Person prototype:


function Student(name, school) {
Person.call(this, name); // Call the Person constructor
this.school = school;
}
// Inherit the greet method
Student.prototype = Object.create(Person.prototype);
const student = new Student('Charlie', 'XYZ School');
student.greet(); // Outputs: 'Hello, my name is Charlie'

Example 3: Overriding Methods


You can override methods in child objects. In this example, we override the greet() method in the Student object:


Student.prototype.greet = function() {
console.log('Hi, I am a student named ' + this.name);
}
student.greet(); // Outputs: 'Hi, I am a student named Charlie'

Conclusion


JavaScript prototypes are powerful for extending and sharing functionality among objects, supporting inheritance, and overriding methods. They promote code reusability and maintainability, making them an essential concept in JavaScript development.


Experiment with different scenarios and use cases to explore the versatility of JavaScript prototypes in your projects.