What is Prototype in JavaScript: Simple Explanation and Examples
prototype is an object that allows other objects to inherit properties and methods. It acts like a blueprint that links objects together, enabling shared behavior without copying code.How It Works
Think of prototype as a shared recipe book for objects. When you create an object, it has a hidden link to a prototype object. If you ask the object for a property or method it doesn't have, JavaScript looks up this link to find it.
This is like borrowing a tool from your neighbor if you don't have it at home. This system is called prototype chaining. It helps save memory because many objects can share the same methods instead of each having their own copy.
Example
This example shows how an object inherits a method from its prototype.
function Person(name) { this.name = name; } Person.prototype.greet = function() { return `Hello, my name is ${this.name}`; }; const alice = new Person('Alice'); console.log(alice.greet());
When to Use
Use prototype when you want many objects to share the same methods or properties without duplicating code. This is common when creating many similar objects, like users or products, to keep your code efficient.
For example, if you build a game with many characters, you can put shared actions like move or attack on the prototype so all characters can use them.
Key Points
- Prototype is an object linked to other objects for sharing features.
- JavaScript uses prototype chaining to find properties or methods.
- It helps save memory by sharing methods instead of copying.
- Constructors and classes use prototypes behind the scenes.