16/33 The "this" keyword. Need help with my code please


#1

here are the instructions:

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. here is my code:

// 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

@dataplayer53575

I looked back at my notes for this task ...

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

// 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);

we can reuse the same method for different objects! This allows us to avoid typing out a custom method each time. All because we used the placeholder this.

...so I think on the last line we don't need the equals sign =

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

try amending last line so the equal sign is not included like so:

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

I run code without equals = sign using javascript in repl.it

https://repl.it/languages/javascript

and checked it printed out to console window the amended age and it worked ok without the equals = sign and showed the amended age.

//check bob's age has been changed;
console.log(bob.age)

Output to console window in repl.it:

Native Browser JavaScript
50


#3

You mistakenly added an = here. it should read bob.setAge(50); since it's a function.