Introduction to Objects I Q&A


#1

Hello everyone, I am stuck, once again, on "This" Works for Everyone, and clearly, it doesn't :stuck_out_tongue_winking_eye:.
I'm not quite sure why it isn't working but I have a feeling I didn't understand what they were asking for. 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;
bob.setAge = setAge;
  
// make susan here, and first give her an age of 25
var susan = new Object():
susan.age = 25;
susan.setAge = setAge;
// here, update Susan's age to 35 using the method
var setage = function (newAge) {
    this.age = newAge;
};

Help me please!
Thanks
camillita


#2

// here, update Susan's age to 35 using the method
var setage = function (newAge) {
    this.age = newAge;
};

Once defined, we never have to define a function again (with provisos that we don't need to get into).

The above lines of code can be removed since they are already in the code at the top. In this segment all we wish to do is invoke the method on Susan's object.

susan.setAge(35);

There is a difference between copying a function and invoking one. This line,

susan.setAge = setAge;

merely copies the function as a string.

"function (newAge) {
    this.age = newAge;
}"

but it is a value for the setAge property of the susan object, so it now reads like,

susan = {
    age: 25,
    setAge: function (newAge) {
        this.age = newAge;
    }
}

When we invoke it on the susan object, we set the age property of that object, this.

susan.setAge(35);
console.log(susan.age);    // 35

#3

Thank you @mtf! Here is my updated and correct 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;
bob.setAge = setAge;
  
// make susan here, and first give her an age of 25
var susan = new Object();
susan.age = 25;
susan.setAge = setAge;
// here, update Susan's age to 35 using the method
susan.setAge(35);
console.log(susan.age);

Thanks again! :smile: