JavaScript Prototypes: Simple and Clear Explanation
Shubham Mansute
Software Engineer at Amdocs ?? JavaScript | TypeScript | React js | Redux js | Next js |Tailwind??
JavaScript is a prototype-based language, which means objects can inherit properties and methods from other objects. Let's break this down in the simplest way possible!
What is a Prototype?
A prototype is like a blueprint or a parent object that other objects can inherit from. Every JavaScript object has a hidden link (__proto__) to another object, known as its prototype.
Why Do We Need Prototypes?
Imagine you are creating multiple objects with the same properties and methods. Without prototypes, you would have to duplicate the same methods in every object, which is inefficient. Instead, prototypes allow objects to share methods, reducing memory usage and improving performance.
Without Prototype (Inefficient)
function Person(name) {
this.name = name;
this.greet = function() {
console.log("Hello, " + this.name);
};
}
const p1 = new Person("Alice");
const p2 = new Person("Bob");
p1.greet(); // Hello, Alice
p2.greet(); // Hello, Bob
Here, every new object gets its own copy of greet, wasting memory.
With Prototype (Efficient)
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log("Hello, " + this.name);
};
const p1 = new Person("Alice");
const p2 = new Person("Bob");
p1.greet(); // Hello, Alice
p2.greet(); // Hello, Bob
Now, greet is shared across all instances, optimizing memory.
Reusing Methods with Prototype
Using prototype, we can define shared methods that all instances of a constructor function can use.
领英推è
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(`${this.name} makes a sound.`);
};
const dog = new Animal("Buddy");
dog.speak(); // Buddy makes a sound.
Here, the speak method is shared among all Animal objects.
__proto__, prototype, and [[Prototype]]
__proto__
- It is a reference to the prototype of an object.
- Every object has a __proto__ property that points to its prototype.
const obj = {};
console.log(obj.__proto__); // logs Object.prototype
prototype
- This is a special property found on functions (not regular objects).
- It is used when creating objects with constructors.
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(`${this.name} makes a sound.`);
};
const dog = new Animal("Buddy");
dog.speak(); // Buddy makes a sound.
Here, Animal.prototype defines the shared method, and every instance (like dog) gets access to it.
[[Prototype]]
- This is an internal property of an object.
- It is what __proto__ refers to behind the scenes.
- JavaScript engines use [[Prototype]] to look up properties and methods.
Understanding prototypes will help you write efficient and optimized JavaScript code!
Learner
1 个月Interesting