In JavaScript, prototypes are a powerful mechanism that allows objects to inherit properties and methods from other objects. Every JavaScript object has an internal property called [[Prototype]] (often referred to as __proto__). This prototype chain allows for the sharing of properties and methods among objects, making it a cornerstone of JavaScript's object-oriented programming capabilities.
The prototype of an object can be accessed through the Object.getPrototypeOf()
method or the __proto__
property. By adding properties or methods to an object's prototype, you effectively add them to all instances of that object, enabling code reuse and organization in your JavaScript applications.
For example, if you have a constructor function for creating "Car" objects, you can define shared properties or methods on its prototype, which can be utilized by all instances of "Car".
// Constructor function for Car
function Car(brand, model) {
this.brand = brand;
this.model = model;
}
// Adding a method to the Car prototype
Car.prototype.details = function() {
return `This is a ${this.brand} ${this.model}.`;
};
// Creating a new Car instance
const myCar = new Car('Toyota', 'Corolla');
console.log(myCar.details()); // Output: This is a Toyota Corolla.
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?