Prototype
Understand the prototype — every JavaScript object has a hidden prototype link that allows objects to share methods and properties.
Prototype
Every object in JavaScript has a hidden property called __proto__ (or [[Prototype]]). This prototype is the mechanism JavaScript uses to share methods and properties between objects.
What Is a Prototype?
function User(name) {
this.name = name;
}
User.prototype.login = function() {
console.log(this.name + ' logged in');
};
var user = new User('Shaun');
console.log(user);
// User { name: 'Shaun' }
// __proto__:
// login: function()
// constructor: function User()
The login method is not on the user object directly — it is on the prototype. JavaScript looks up the prototype chain to find it.
The Prototype Chain
user.login()
↓
Does user have a 'login' property? No.
↓
Check user.__proto__ (User.prototype) → Found! Execute it.
user.toString()
↓
Does user have 'toString'? No.
↓
Check User.prototype → No.
↓
Check Object.prototype → Found! Execute it.
Visualizing the Chain
user (instance)
└── __proto__ → User.prototype
├── login()
└── __proto__ → Object.prototype
├── toString()
├── hasOwnProperty()
└── __proto__ → null (end of chain)
Checking Prototypes
// What is on the prototype?
console.log(User.prototype);
// { login: function, constructor: function User }
// Is this method on the instance or prototype?
console.log(user.hasOwnProperty('name')); // true (own property)
console.log(user.hasOwnProperty('login')); // false (on prototype)
Why Prototypes Matter
| Approach | Memory Usage | Shared? |
|---|---|---|
| Method in constructor | Duplicated per instance | No |
| Method on prototype | Stored once | Yes — all instances share it |
Key Takeaways
- Every object has a
__proto__linking to its prototype - JavaScript walks up the prototype chain to find properties and methods
- Prototype methods are shared across all instances — efficient for memory
hasOwnProperty()checks if a property is on the instance vs the prototype