Prototype-based inheritance is a mechanism in JavaScript that allows objects to inherit properties and methods from other objects. Every object in JavaScript has an internal prototype property, which is a reference to another object. When a property or method is accessed on an object, JavaScript first looks for the property or method on the object itself. If it is not found, it then looks for it on the object’s prototype. This process continues up the prototype chain until the property or method is found, or until the end of the chain is reached (which is usually the Object.prototype object).
Here’s an example:
// Define a Person constructor function
function Person(name, age) {
this.name = name;
this.age = age;
}
// Add a method to the Person prototype
Person.prototype.sayHello = function() {
console.log("Hello, my name is " + this.name);
};
// Create a new object using the Person constructor
var john = new Person("John", 30);
// Call the sayHello method on the john object
john.sayHello(); // Outputs "Hello, my name is John"
In this example, we define a constructor function Person that takes two arguments: name and age. We then add a method sayHello to the Person.prototype object. When we create a new object john using the Person constructor, it automatically inherits the sayHello method from its prototype.
Prototype-based inheritance is different from classical inheritance in languages such as Java or C++, where classes define the structure and behavior of objects. In JavaScript, there are no classes, only objects. Instead of defining a class and creating instances of it, you define a constructor function and use the new keyword to create new objects that inherit properties and methods from the constructor’s prototype.
In summary, prototype-based inheritance is a mechanism in JavaScript that allows objects to inherit properties and methods from other objects. Every object in JavaScript has an internal prototype property, which is a reference to another object. This allows for dynamic object creation and easy object extension.