Explain Prototype Inhe...
Explain Prototype Inhe...
Prototype inheritance in JavaScript is a feature that allows objects to inherit properties and methods from other objects. This is a fundamental concept in JavaScript because it enables object-oriented programming patterns.
In JavaScript, every object has a hidden internal property known as [[Prototype]]
, which can be either null
or a reference to another object. This referenced object is known as the prototype. When you attempt to access a property or method on an object, and it does not exist on the object itself, JavaScript will look up the property or method on the object's prototype. If it still doesn't find it there, it will continue searching up the prototype chain until it reaches null
. If the property or method is found on a prototype, it is inherited.
The prototype chain is the mechanism that JavaScript uses to perform this lookup and inheritance. It is a series of linked prototypes that JavaScript traverses to search for properties and methods. The chain ends when a prototype is null
, which is the prototype of Object.prototype
.
Here's a simple example to illustrate prototype inheritance:
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(`${this.name} makes a noise.`);
};
function Dog(name) {
Animal.call(this, name); // Call the Animal constructor function
}
// Set Dog's prototype to be an instance of Animal
Dog.prototype = Object.create(Animal.prototype);
// Set the constructor property to refer to Dog
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function() {
console.log(`${this.name} barks.`);
};
let d = new Dog('Mitzie');
d.speak(); // Mitzie makes a noise.
d.bark(); // Mitzie barks.
In this example, Dog
inherits from Animal
. We set the prototype of Dog
to be an instance of Animal
using Object.create()
. This means that instances of Dog
will have access to methods defined on Animal.prototype
, such as speak
. We also define a new method bark
on Dog.prototype
, wh...
senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào