The "this" keyword


I have absolutely no idea how to do this. Can you help me?


Could you please post the instructions so I could walk you through it?


Our setAge method works great for bob because it updates bob.age, but what if we want to use it for other people?

It turns out we can make a method work for many objects using a new keyword, this. The keyword this acts as a placeholder, and will refer to whichever object called that method when the method is actually used.

Let's look at the method setAge (line 2) to see how this works. By using the keyword this, setAge will change the age property of any object that calls it. Previously, we had a specific object bob instead of the keyword this. But that limited the use of the method to just bob.

Then when we say bob.setAge = setAge; (line 9), it means whenever we type bob.setAge( ), this.age in the setAge method will refer to bob.age.

To show this way of making setAge works just like the one in exercise 2, use bob's setAge method to change his age to 50.



Simplified Instructions:
Your goal here is to make setAge available to any person object.
You want to do this with the this keyword.

First, you want to create the setAge function as so:

var setAge = function(this) { //Passing in this, as we will need it later.


Think of the this keyword as an object. It could be mary or john or anyone else.

Remember, you can set an object's values like this:

mary.age = 21;

We are going to need to use this to substitute for the object like so:

this.age = 21;

Now we add it into the function:

var setAge = function(this) {
this.age = 21;

The only thing is, we want to set a different age for each person, so we add an age parameter:

var setAge = function(this, age) {
this.age = age;

And there you go! You can update an object with setAge like so:

mary.setAge = setAge();
//Set to 21
//Set to 300



Thanks that helped a lot


You're welcome!

Just post again if you're confused! :slightly_smiling:


A post was split to a new topic: "Object Expected" error?


A post was split to a new topic: Plz explain this