Great! Now we can take advantage of the fact that the method setAge is not limited to a single object bob—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.
In the editor, we have the same code as last time, where we define setAge using this. We then set bob.setAge = setAge;. But this time we will reuse the setAge method for susan as well.
Instructions
Make
susan
on lines 11-13, who should initially have an age of 25
and a susan.setAge
method also equal to setAge
.
Then use
susan.setAge(35);
to set susan
's age to 35
.
// 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);
No comments:
Post a Comment