In JavaScript, the prototype chain is a mechanism through which objects inherit properties and methods from other objects. It is a core concept in JavaScript’s prototype-based inheritance model.
Every JavaScript object has an internal property called [[Prototype]], which points to another object. You can access an object's prototype using the __proto__ property (though using Object.getPrototypeOf() is preferred).
When you try to access a property or method on an object, JavaScript searches:
null, which is the end of the prototype chain.alice.greet() checks if greet is on alice — it is not.alice.__proto__ (which is Person.prototype), and finds greet.greet wasn't there, it would look up Person.prototype.__proto__ (which is Object.prototype).null and stop searching.Object.prototype is at the top of every prototype chain.Object.getPrototypeOf() is the standard way to get an object’s prototype..toString() and .hasOwnProperty() come from Object.prototype.class Syntax in JavaScriptIn modern JavaScript, the class syntax provides a cleaner and more intuitive way to create objects and manage inheritance. However, under the hood, class still uses prototypes to establish the inheritance chain.
dog object: JavaScript first looks for speak() and bark() on dog directly.Dog.prototype: If not found on dog, it looks up Dog.prototype.Animal.prototype: If not found there, it looks up Animal.prototype.Object.prototype: Finally, it checks Object.prototype.null: If the property isn't found anywhere, it returns undefined.class Example:class and prototype):The class syntax is syntactic sugar for the older prototype-based approach. The following code produces the same result as the class-based example:
class is a cleaner way to implement prototypes and inheritance.extends sets up the prototype chain.super() calls the constructor of the parent class.Would you like to explore more examples, such as method overriding or multiple inheritance patterns? 😊