Prototype - The Backbone of JavaScript Object
Understanding Prototypes in JavaScript
Prototype plays a crucial role in how objects inherit properties and methods. Understanding prototypes helps in writing efficient and scalable JavaScript code.
A prototype in JavaScript is like a blueprint or template that objects can inherit from, Here’s a real-life analogy to explain it.
Evolution of Prototype
The evolution of a prototype refers to the stages a product prototype undergoes, from an initial concept to a refined, market-ready version. It involves iterative development, feedback loops, and continuous improvement.
1. Conceptualization Phase
Identify the problem and define the solution.
Create rough sketches, wireframes, or low-fidelity prototypes.
Focus on the idea rather than the implementation.
2. Proof of Concept (PoC)
Develop a basic model to test feasibility.
Demonstrate whether the core idea is technically possible.
No focus on design, just validating functionality.
3. Low-Fidelity Prototype
Build a simple, non-functional mockup.
Could be paper-based or a rough digital model.
Used for early feedback and brainstorming.
4. High-Fidelity Prototype
A more refined version with better UI/UX.
Interactive elements are introduced.
Used for user testing to validate usability.
5. Functional Prototype
A working version with core functionalities.
Built using actual technologies (hardware/software).
Helps developers and designers refine features.
6. Pre-Production Prototype
Close to the final version but still in testing.
Tested for scalability, performance, and manufacturability.
Used for beta testing or pilot runs.
7. Final Product
The refined version ready for full-scale production or deployment.
Incorporates feedback from all previous stages.
Meets industry standards and user expectations.
Real Life Analogy-
Imagine your grandmother has a special recipe book that contains various traditional dishes. This book serves as a prototype—it has instructions, ingredients, and methods for cooking.
Now, when your mother (a new object) wants to make a dish, she doesn’t need to reinvent the recipe; she simply inherits the recipe from the book. She can also add her own custom modifications, like adjusting spice levels.
Similarly, in JavaScript:
The prototype is like the recipe book—it holds default properties and methods.
Objects created from it (like children or grandchildren) inherit these methods but can override or extend them if needed.
This explains why JavaScript objects can access methods from their prototype chain without redefining them.
What is a Prototype?
Every JavaScript function comes with a special property called prototype
. This is just an object where we can store properties and methods that other objects can use.
When we create an object using a constructor function or Object.create()
, the new object gets a link to this prototype
object. This link allows it to inherit properties and methods, even if they are not directly inside the object.
This process creates a prototype chain, where JavaScript keeps looking for a property up the chain until it finds it or reaches the top (which is null
). This is how inheritance works in JavaScript!
How Prototype Works
When you try to access a property or method of an object, JavaScript first checks if that property exists in the object itself. If not, it looks up the prototype chain until it either finds the property or reaches null
.
Example 1: Understanding Prototype Inheritance
function Person(name, age) {
this.name = name;
this.age = age;
}
// Adding a method to the prototype
Person.prototype.greet = function() {
return `Hello, my name is ${this.name}`;
};
const user1 = new Person("Himanshu", 24);
console.log(user1.greet()); // Output: Hello, my name is Himanshu
Here, greet()
is not defined inside user1
, but JavaScript finds it in Person.prototype
.
Prototype Chain
A prototype can also have its own prototype, creating a prototype chain. This chain continues until it reaches Object.prototype
, which is the root of all objects in JavaScript.
A prototype can also have its own prototype, forming a chain.
Think of it like a family tree:
If an object doesn’t have a property, JavaScript checks its prototype (like asking a parent).
If the prototype also doesn’t have it, JavaScript looks further up the chain (like asking grandparents).
This continues until it reaches Object.prototype, which is the top-most ancestor of all objects.
console.log(user1.__proto__ === Person.prototype); // true
console.log(Person.prototype.__proto__ === Object.prototype); // true
console.log(Object.prototype.__proto__); // null
Since Object.prototype.__proto__
is null
, the lookup stops there.
Using Object.create()
for Prototypal Inheritance
we can use
Object.create()
to make one object inherit from another.Think of it like copying a blueprint! The new object gets access to all the properties and methods of the original object.
const car = {
type: "Sedan",
drive() {
console.log("Driving a car...");
}
};
const myCar = Object.create(car);
myCar.brand = "Toyota";
console.log(myCar.type); // Output: Sedan
myCar.drive(); // Output: Driving a car...
console.log(myCar.__proto__ === car); // true
myCar
inherits properties from car
but can also have its own properties.
Modifying Built-in Prototypes
We can modify built-in prototypes like Array.prototype
or String.prototype
, but it's generally not recommended as it can lead to unexpected behavior.
Array.prototype.last = function() {
return this[this.length - 1];
};
const nums = [10, 20, 30];
console.log(nums.last()); // Output: 30
Modifying native prototypes can cause conflicts in larger projects.
ES6 Classes and Prototype
JavaScript classes are just syntactic sugar over prototypes.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound.`;
}
}
const dog = new Animal("Dog");
console.log(dog.speak()); // Output: Dog makes a sound.
console.log(dog.__proto__ === Animal.prototype); // true
Even though we use class
, under the hood, JavaScript still relies on prototypes for inheritance.
Conclusion
Prototypes are fundamental to JavaScript’s object model.
Prototype chaining allows objects to inherit properties and methods.
Object.create()
is an alternative way to create objects with a specific prototype.Avoid modifying built-in prototypes unless absolutely necessary.
ES6 classes internally use prototypes but offer a cleaner syntax.
Read More Article...
I’m truly thankful for your time and effort in reading this.