Inheritance in JavaScript works primarily through prototype chaining. When an object is created, it has a hidden internal link to another object, known as its prototype. This prototype itself can have its own prototype, and so on, forming a chain. When a property or method is accessed on an object, JavaScript will look up the chain until it finds the property, or returns undefined if it doesn't exist.
Here’s a basic example demonstrating inheritance in JavaScript:
// Base class
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(this.name + ' makes a noise.');
};
// Derived class
function Dog(name) {
Animal.call(this, name); // Call the parent constructor
}
// Inherit from Animal
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
// Overriding speak method
Dog.prototype.speak = function() {
console.log(this.name + ' barks.');
};
// Example usage
const dog = new Dog('Rex');
dog.speak(); // Output: Rex barks.
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?