JavaScript Prototype Methods & Objects Without __proto__
JavaScript uses prototypal inheritance, where objects inherit properties and methods from a prototype. Let's explore prototype methods and how to create objects without __proto__
.
š¹ Understanding prototype
in JavaScript
Every JavaScript function automatically has a prototype
property, which is an object that will be inherited by instances created using the new
keyword.
✅ Example: Adding Methods via prototype
✔ The sayHello()
method is shared among all User
instances.
š¹ Objects Without __proto__
By default, JavaScript objects inherit from Object.prototype
, meaning they have a __proto__
property. However, we can create objects without a prototype using Object.create(null)
, preventing prototype-based inheritance.
✅ Example: Object Without __proto__
✔ This object has no inherited methods (e.g., toString()
, hasOwnProperty()
).
š¹ When to Use Objects Without __proto__
?
✔ Security: Prevents prototype pollution attacks.
✔ Performance: Reduces overhead from unwanted inherited properties.
✔ Pure data storage: Acts like a plain hash map.
✅ Example: Using Objects Without Prototypes as a Dictionary
✔ This avoids issues where built-in Object.prototype
methods interfere.
šÆ Summary
✔ prototype
allows methods to be shared across object instances.
✔ Object.create(null)
creates an object without prototype inheritance.
✔ Useful for security, performance, and clean data storage.
š Need more examples? Let me know! š