16. Help on the "The "this" Keyword"


#1


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


Code works. My question is, why did we need to include:

Bob.setAge = setAge

Couldn't we have just adjusted the age by writing;
Bob.setAge(50)


// 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 can delete setAge method, but then you would need to create this method on bob's object.
This will work too:

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

By setting bob.setAge property value as a variable that holds a function you can reuse that function, so now it can work on bob's object. Of course to gain some performance it's best to create that method on prototype object.

By your given code setAge method can be reused many times, you can change behavior or function body and it will take effect on every object that has this method assigned somewhere.


#3

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