JavaScript Object Prototypes
14 April 2025 | Category: JavaScript
In JavaScript, every object has a prototype. A prototype is another object that your object inherits properties and methods from.
Think of prototypes as a blueprint or parent object from which other objects can get shared behavior.
đ What Is a Prototype?
When you create a JavaScript object, it automatically gets linked to a prototype object. This allows property and method sharing between objects.
Example:
const person = {
greet: function() {
console.log("Hello!");
}
};
const user = Object.create(person);
user.greet(); // Output: Hello!
Here:
user
doesnât have its owngreet()
method.- JavaScript looks up the prototype chain and finds
greet()
inperson
.
đ§ Understanding the Prototype Chain
When you try to access a property or method on an object:
- JavaScript first checks if it’s in the object itself.
- If not found, it looks at the objectâs prototype.
- It keeps going up the chain until it finds the property or reaches
null
.
user â person â Object.prototype â null
đ ď¸ Using __proto__
(not recommended in production)
const obj = {};
console.log(obj.__proto__); // Shows Object.prototype
__proto__
is a getter/setter for an objectâs internal prototype. Use it only for learning or debugging.
đ§ą Every Function Has a prototype
Property
When you create a function, it automatically gets a .prototype
object:
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.
speak()
is defined onAnimal.prototype
- All objects created using
new Animal()
share this method
đ Difference: prototype
vs __proto__
Term | Meaning |
---|---|
prototype | A property of constructor functions used when creating new objects |
__proto__ | The actual internal prototype link of an object (points to another object) |
â Benefits of Using Prototypes
- Memory efficient: Methods are shared across instances instead of copied
- Inheritance: Makes it easier to create parent-child relationships between objects
- Foundation of JS OOP: Classes in JavaScript are syntactic sugar over prototype-based inheritance
đĄ Modern Use: Classes Behind the Scenes
When you use ES6 classes, JavaScript still uses prototypes under the hood:
class User {
sayHi() {
console.log("Hi!");
}
}
const u1 = new User();
u1.sayHi(); // Inherited from User.prototype