Why "this" is not working in my code?


#1

var bob = {
firstName: "Bob",
lastName: "Jones",
phoneNumber: "(650) 777-7777",
email: "bob.jones@example.com"
};

var mary = {
firstName: "Mary",
lastName: "Johnson",
phoneNumber: "(650) 888-8888",
email: "mary.johnson@example.com"
};

var contacts = [bob, mary];

var printPerson = function (person) {
console.log(this.firstName + " " + this.lastName);
};
printPerson(bob);
printPerson(mary);


#2

You wouldn't use the keyword this in this context. The this keyword would be used when you've created an Object constructor. For example:

function Dog(name, age, weight) {
	this.name = name;
  this.age = age;
  this.weight = weight;
};

See for full example: https://jsfiddle.net/cheekybastard/9w3kgjru/

In this case, you don't need (and haven't used) this in an Object constructor.

Instead, you've included the parameter person for your function. So, you want to use this parameter inside the function's code--in this case, when you're trying to print with console.log.

var printPerson = function (person) {
console.log(person.firstName + " " + person.lastName);
};

Also, when you're calling the function (the last two lines of your code), you want to make sure you're referencing the position of each object in the array. Remember, that arrays are indexed based on 0--where 0 is the first position, 1 is the second position, etc.

So, suppose you had this array:

var pets = [Rover, Snoopy, Lassie];

To access, "Snoppy", you'd need to do this:

console.log(pets[1]);

Notice that in console.log that I'm referring to the variable that names the array, not the variables that name the objects themselves. And note that after the reference to the array, I've added the numeric position of what I want to access in brackets.

So, in the last two lines of your code, make sure to reference the name of the array and the position of each object.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.