Unlike languages like Java or C++ which use class-based inheritance, JavaScript uses prototype-based inheritance. In JavaScript, objects inherit features and properties from other objects.
What is a Prototype?
Every object in JavaScript has a link to a prototype object. When you attempt to access a property on an object, JavaScript first looks at the object itself. If the property isn't found, it climbs the prototype chain to check the prototype object, continuing until the prototype chain ends (pointing to null).
Object.__proto__ vs Constructor.prototype
A common point of confusion is the difference between __proto__ and prototype:
__proto__: An accessor property on every object that points to its actual prototype (also retrieved viaObject.getPrototypeOf()).prototype: A property present on constructor functions (and classes) that defines what__proto__will be assigned to objects created using thenewkeyword.
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
return "Hello, my name is " + this.name;
};
const user = new Person("Nirali");
console.log(user.__proto__ === Person.prototype); // true
console.log(user.greet()); // "Hello, my name is Nirali"