The "this" Keyword


#1


The "this" Keyword

Getting Error : Oops, try again. It looks like you have an error in your code. Here's the message: TypeError: bob.setAge is not a function.

Can anyone help with this please..


// here we define our method using "this", before we even introduce bob
var setAge = function (newAge) {
  this.age = newAge;
};
// now we make bob
var bob = new Object();
bob.age = 30;
// and down here we just use the method we already made
bob.setAge = setAge();
  
// change bob's age to 50 here
bob.setAge(50);


#2

You're supposed to be assigning a variable to the bob.setAge property, which will itself contain the function, rather than calling the function with setAge()


#3

Thanks for response.
But sorry, I don't get it.

I tried this - "bob.setAge = setAge(50);"
and this comes up - "Oops, try again. Make sure to change bob's age to 50!"


#4

Think of it this way - you define the function at the top of the page:

var setAge = function (newAge) {
  this.age = newAge;
};

Now in order to call this function, you'd type setAge() (with or without a parameter).

This means that if you type bob.setAge = setAge(); you're not assigning the function to bob.setAge, but rather the result of the function (which incidentally is nothing, since there's no return value).

If you type bob.setAge = setAge, you're using the variable you defined at the start (which is the function itself) rather than the result of the function.


#5

here is the correct answer :

var setAge = function (newAge) {
this.age = newAge;
};
// now we make bob
var bob = new Object();
bob.age = 30;
// and down here we just use the method we already made
bob.setAge = setAge;

// change bob's age to 50 here
bob.setAge(50);