Common Mistakes: Confusing the Two
You'll learn: How to avoid mixing up Function.prototype and obj.__proto__ in real-world situations.
Now that you understand the difference between these two prototype concepts, let's address the most common mistakes beginners make when working with them.
The Classic Mix-Up
The biggest confusion happens when trying to add shared methods. Remember:
Function.prototypeis the property on constructor functions where you add methods for all instancesobj.__proto__is the accessor on instances that points to the constructor's prototype
Wrong approach:
function Dog(name) {
this.name = name;
}
// Mistake: trying to add methods to an instance's __proto__
const dog1 = new Dog('Buddy');
dog1.__proto__.bark = function() { console.log('Woof!'); };
// This works, but modifies the shared prototype indirectly
Right approach:
// Correct: add methods directly to the constructor's prototype property
Dog.prototype.bark = function() { console.log('Woof!'); };
Why It Matters
Both approaches technically modify the same object (the constructor's prototype), but using __proto__ is indirect, deprecated, and confusing. Always use the constructor's prototype property when you want to add shared functionality.
When to Use Each
- Use
Constructor.prototype.method = ...when defining shared methods - Use
Object.getPrototypeOf(obj)when reading an object's prototype (avoid__proto__) - Never manually set
obj.__proto__in production code
Key Takeaway: Add shared methods to the constructor's prototype property, not through an instance's __proto__. Think of prototype as the blueprint where you write methods, and __proto__ as just a way to read the connection.