Explain Prototype Inheritance in JavaScript
Prototype Inheritance is a mechanism in JavaScript that allows objects to inherit properties and methods from other objects. In JavaScript, every object has a prototype object, which acts as a template for the object. When a property or method is accessed on an object, JavaScript first looks for it on the object itself. If it is not found, it looks for it on the object's prototype. If it is still not found, it looks for it on the prototype's prototype, and so on, until it reaches the end of the prototype chain.
There are two main ways to create objects in JavaScript: using object literals and using constructor functions.
- Object Literals: When an object is created using an object literal, its prototype is automatically set to the Object.prototype object. For example:
let person = {
name: "John",
age: 30,
greet: function() {
console.log("Hello, my name is " + this.name);
}
};
console.log(person.name); // "John"
person.greet(); // "Hello, my name is John"
console.log(person.toString()); // "[object Object]"
In the above example, the person
object is created using an object literal. Its prototype is automatically set to the Object.prototype
object. The name
and age
properties are defined on the person
object itself, while the greet
method is defined on the Object.prototype
object and is inherited by the person
object.
- Constructor Functions:
When an object is created using a constructor function, its prototype is set to the constructor function's
prototype
property. For example:
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function() {
console.log("Hello, my name is " + this.name);
};
let person = new Person("John", 30);
console.log(person.name); // "John"
person.greet(); // "Hello, my name is John"
console.log(person.toString()); // "[object Object]"
In the above example, the Person
constructor function is defined with a name
and age
parameter. The greet
method is defined on the Person.prototype
object. When a new Person
object is created using the new
keyword, its prototype is set to the Person.prototype
object. The name
and age
properties are defined on the person
object itself, while the greet
method is inherited from the Person.prototype
object.
In summary, prototype inheritance allows objects to inherit properties and methods from other objects. It is a powerful feature of JavaScript that allows for code reuse and object-oriented programming.