What is prototype and prototypal inheritance in JavaScript?
Every object has a hidden link to another object called its prototype. When you read a property that the object does not have, JavaScript looks for it in the prototype, then in the prototype of the prototype, and so on. This chain is prototypal inheritance.
function Person(name) {
this.name = name;
}
Person.prototype.greet = function () {
return "Hi, " + this.name;
};
const p = new Person("Robin");
console.log(p.greet());
console.log(Object.getPrototypeOf(p) === Person.prototype);
Output:
Tutorials Class - Output Window
Hi, Robin
true
class and extends are a nicer syntax over the same prototype system. See Constructor Functions and Classes.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |