Reputation: 136
I have 2 objects which is bob and mary and i want to call their firstName and lastName values in a function with using an array but this code doesn't seem to work
var bob = {
firstName: "Bob",
lastName: "Jones",
phoneNumber: "(650) 777-7777",
email: "[email protected]"
};
var mary = {
firstName: "Mary",
lastName: "Johnson",
phoneNumber: "(650) 888-8888",
email: "[email protected]"
};
var contacts = [bob, mary];
var printPerson = function(person) {
console.log(this.firstName + " " + this.lastName);
}
printPerson(contacts[0]);
printPerson(contacts[1]);
What am i missing ?
Upvotes: 0
Views: 28
Reputation: 26
You need to access firstName and lastName attributes from person parameter. So, your code must be:
var printPerson = function(person){
console.log(**person**.firstName + " " + **person**.lastName);
}
Upvotes: 1
Reputation: 87233
In your function this
refers to the window
object.
Use the object that is passed to the function as parameter.
Use person.firstName
and person.lastName
to get the names from the respective object.
var printPerson = function(person) {
console.log(person.firstName + " " + person.lastName);
// ^^^^^^ ^^^^^^
}
Upvotes: 2