Consider this scenario where I have JSON data containing person objects.
[
{
"name": "Alice",
"age": 28,
},
{
"name": "Bob",
"age": 33
}
]
Upon parsing, an array with two JavaScript objects is obtained. Suppose I want to add a method called introduce to these objects, which would look something like this:
function introduce() {
return "My name is " + this.name + " and I am " + this.age + " years old.";
}
One way to achieve this would be iterating over the objects and calling:
person.constructor.prototype.introduce = introduce
However, this approach will make the introduce function accessible to all JavaScript objects, not just the intended ones.
Alternatively, manually attaching the function to each object can be done, but in case of adding more functions later, it would require iterating over all objects again.
Ideally, having a prototype that can be fitted with the introduce
method and then connected to all person objects would be preferred. This way, if the prototype is extended in the future, the added functions will also be available to the person objects.
The query now arises: how can this be achieved?