Let's say I have the following JSON with person objects.
[
{
"name": "Alice",
"age": 28,
},
{
"name": "Bob",
"age": 33
}
]
If I parse this, I will get an array with two JavaScript objects. Let's say, I want to equip these two objects with a method called introduce, that does something like this
function introduce() {
return "My name is " + this.name + " and I am " + this.age + " years old.";
}
Now, I could iterate over my two people and call
person.constructor.prototype.introduce = introduce
However, this will expose the introduce function in ALL JavaScript objects, not just the two above.
I could also manually attach the function to each object, but if I want to extend my people with additional functions, I will have to iterate over all people again.
Ideally, I would like a prototype that I can fit with the introduce method and then attach this prototype to all my people, so if I later extend the prototype, my people will gain additional functions as well.
The question is: how?
person.prototype.introduce = introduceand get rid of theconstructorpart.Personclass, parse json to makePerson. Anytime add any function toPersonprototype.personis his reference to the object itself, soperson.prototypewon't exist.JSON.parsefor this specific purpose, usingObject.setPrototypeOf(check my answer).