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?
The Object. setPrototypeOf() method sets the prototype (i.e., the internal [[Prototype]] property) of a specified object to another object or null. All JavaScript objects inherit properties and methods from a prototype. It is generally considered the proper way to set the prototype of an object.
As you can see in the above example, Function's prototype property can be accessed using <function-name>. prototype. However, an object (instance) does not expose prototype property, instead you can access it using __proto__ .
Note: The property of an object that points to its prototype is not called prototype . Its name is not standard, but in practice all browsers use __proto__ . The standard way to access an object's prototype is the Object. getPrototypeOf() method.
I suggest you to create a class:
JSBin
var Person = (function () {
function Person(person) {
this.person = person;
this.name = person.name;
this.age = person.age;
}
Person.prototype.introduce = function () {
return "My name is " + this.name + " and I am " + this.age + " years old.";
};
return Person;
})();
You're question is a little fuzzy to understand. But I think you don't want your "person" to be a regular object, but rather a separate person "class:"
var Person = function(obj){
this.name = obj.name;
};
Person.prototype.introduce = function(){
return console.log('hi, I\'m '+this.name);
};
var personA = new Person({ name:'a' });
var personB = new Person({ name:'b' });
personA.introduce(); // "hi, I'm a"
personB.introduce(); // "hi, I'm b"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With