The prototype chain is a fundamental concept in JavaScript that allows objects to inherit properties and methods from other objects. This inheritance happens through a chain of prototypes. Understanding the prototype chain is crucial for mastering JavaScript's object-oriented programming features.
Every object in JavaScript has a prototype. This prototype is itself an object. When you try to access a property or method on an object, JavaScript first checks if the object itself has that property. If not, it looks at the object's prototype. This process continues up the chain of prototypes until the property is found or the end of the chain is reached (null).
function Animal(name) {
this.name = name;
}
Animal.prototype.sayName = function() {
console.log("My name is " + this.name);
};
function Dog(name, breed) {
this.name = name;
this.breed = breed;
// Dog inherits from Animal
}
// Dog inherits from Animal
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog; // Reset constructor
Dog.prototype.bark = function() {
console.log("Woof!");
};
Let's illustrate with an example:
function Person() {
this.age = 0;
}
Person.prototype.getOlder = function(years) {
this.age += years;
console.log("I am now " + this.age + " years old.");
};
function Employee(name, salary) {
Person.call(this, name); // Call Person's constructor
this.salary = salary;
}
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;
var employee = new Employee("Alice", 50000);
employee.getOlder(3); // Calls getOlder inherited from Person
employee.bark(); // Error! bark() is not defined on Employee