Explain how prototypal inheritance works in js
- User
Explain how prototypal inheritance works in js
- Assistant
In JavaScript, every object has a hidden property called
__proto__, which points to another object. This linked object is known as the object's prototype. When you access a property or method on an object, JavaScript first looks for that property or method on the object itself. If it cannot find it, it looks for it on the object's prototype. If it doesn't find it there, it continues up the prototype chain until it either finds the property or reaches the end of the chain.When you create a new object in JavaScript, you can specify another object as its prototype. This establishes a prototypal inheritance relationship, where the new object inherits properties and methods from its prototype.
For example, consider the following code:
let animal = { type: 'mammal', sound: function() { console.log('Makes a sound'); } }; let dog = { breed: 'labrador' }; dog.__proto__ = animal; console.log(dog.breed); // Output: 'labrador' dog.sound(); // Output: 'Makes a sound' console.log(dog.type); // Output: 'mammal'