Javascript Prototypes and inheritance
JavaScript allows objects to inherit attributes and functionality from other objects. Prototypes are used to do this. A prototype is a piece of art that other pieces can use as a model to build upon.
Example:
// Define a prototype object for Person
const PersonPrototype = {
greet: function() {
console.log(`Hello, my name is ${this.name}.`);
}
};
// Define a constructor function for Person
function Person(name) {
this.name = name;
}
// Set the prototype of the Person constructor to be the PersonPrototype object
Person.prototype = PersonPrototype;
// Create a new person object
const john = new Person('John');
// Call the greet method on the person object
john.greet(); // Outputs: "Hello, my name is John."
In this illustration, we define the prototype object PersonPrototype, which has just the greet method. Then, we create a function Object() { [native code] } function for Person that accepts a name parameter and sets it as the value of the new object’s name property. Finally, we set the PersonPrototype object as the prototype of the Person constructor, causing any subsequent Person objects to inherit the prototype’s greet method.
The greet method is then called on the newly created John Person object. John may access and call the greet method since it derives from the PersonPrototype object.
Prototypes are a powerful feature of JavaScript that allows for flexible and dynamic object-oriented programming. They enable us to create complex object hierarchies and reuse code efficiently.