Help with "this" keyword


#1

https://www.codecademy.com/en/courses/spencer-sandbox/2/5?curriculum_id=506324b3a7dffd00020bf661

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

i can't understand why do we need to mention susan.setAge = setAge; in the given exercise.
could somebody please help me with this one

Replace this line with your code.


#4

I think that actually

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

is not a method. I believe that it just a function assigned to variable. But here

...
bob.setAge = setAge;
...
susan.setAge = setAge;

we created methods for bob and susan objects and assigned them to variable setAge which is a function that sets age for current object. So, in function

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

this takes susan and bob. So

susan.setAge(35);

means that setAge calls setAge function and put 35 as an argument. In this case function looks like:

var setAge = function (35) {
   susan.age = 35;
};

If I'm wrong, please, someone correct me.


#5

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