JavaScript
Prototype (Prototypal inheritance)
A prototype is an object from which other objects can inherit properties and methods.
Every object in JavaScript has an internal link[[Prototype]], which points to another object ornull.
Prototype Chain
- If a property is not found in an object, the search continues through its prototype chain.
- This chain forms the inheritance mechanism known as the prototype chain.
- The end of the chain is
Object.prototype, after which comesnull.
const obj = {};
console.log(obj.__proto__ === Object.prototype); // trueConstructor Functions and prototype
- Every function in JS has a
prototypeproperty. - Objects created via
newinherit properties and methods fromFunction.prototype.
function User(name) {
this.name = name;
}
User.prototype.sayHi = function() {
return `Hi, ${this.name}`;
};
const user = new User('Alex');
console.log(user.sayHi()); // 'Hi, Alex'Object.create()
Creates a new object with the specified prototype:
const person = { greet() { return 'Hello'; } };
const user = Object.create(person);
console.log(user.greet()); // 'Hello'Key Idea
- A prototype is a mechanism for delegating properties.
- All objects inherit from
Object.prototypeunless specified otherwise. - The prototype model is at the core of classes (
class) and inheritance in modern JavaScript.