JavaScript Prototype Methods & Objects Without __proto__

JavaScript Prototype Methods & Objects Without __proto__

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

function User(name) { this.name = name; } // Add a method to the prototype User.prototype.sayHello = function () { console.log(`Hello, my name is ${this.name}`); }; const user1 = new User("Alice"); user1.sayHello(); // ✅ Output: Hello, my name is Alice

✔ 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__

let obj = Object.create(null); obj.name = "No Prototype"; console.log(obj.name); // ✅ Output: No Prototype console.log(obj.__proto__); // ✅ Output: undefined console.log(Object.getPrototypeOf(obj)); // ✅ Output: null

✔ 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

let dictionary = Object.create(null); dictionary["apple"] = "A fruit"; dictionary["table"] = "An object to place items on"; console.log(dictionary["apple"]); // ✅ Output: A fruit console.log(dictionary.toString); // ✅ Output: undefined (No prototype methods)

✔ 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! 😊

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close