lunaks
lunaks

Reputation: 136

Calling object members in a function

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

Answers (2)

Arlington Rodrigues
Arlington Rodrigues

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

Tushar
Tushar

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

Related Questions