16 The "This" Keyword Explanation Needed


Here is the code:

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

var bob = new Object();
bob.age = 30;

bob.setAge = setAge;


What is "bob.setAge = setAge" doing?
How come I can't just use bob.setAge(50)?
Shouldnt the code know that the 50 goes to the method "setAge" which goes to "this" (being bob), which then changes bob.age to 50? I don't see where the bob.setAge = setAge comes into play


to follow up, the following section results in this code...

var rectangle = new Object();
rectangle.height = 3;
rectangle.width = 4;

rectangle.setHeight = function (newHeight) {
this.height = newHeight;

rectangle.setWidth = function (newWidth) {
this.width = newWidth;



I'm a beginner, so please correct me if I'm wrong.

bob.setAge = setAge is necessary because when you put the following line which is bob.setAge(50), the value 50 is passed to setAge, which is then passed to setAge in 1st line.

newAge then gets the value 50 and passes to this.age in line 2.

The keyword this is just a placeholder and can be substituted with anything that fits the criteria, i.e. the whole thing must end with .age.

In this example, the keyword this gets substituted with bob.

Therefore bob.age now gets the value of 50.


bob.setAge = setAge;

is necessay because when the setAge function is declared in line 2, it is just a function and not a method of any object.

bob.setAge = setAge; makes the setAge function a method of bob. Without it Bob has no idea what you are talking about.


This answer should be added to the lesson. I knew I need the line, cause I tried removing it, changing two, or three of setAges into something else, all cause the line was clearly needed for the code to work, but seemed utterly redundant, basically saying setAge is setAge, like, "no, it can't be so".

There are quite a few holes in these lessons that could use clarification. Once it used if (true) { //something, something } and only two lessons later it explained that that is a legitimate statement, that it doesn't need to use a relation. Now it seems simple enough, but when I run it first time, it was mind boggling.

Because explanations such as this one are lacking, occasionally learner has no choice but to copy paste the bit of code from the forum and move on, w/o any chance of understanding the purpose of the said code.

For most part lessons are easy to follow, except when they are not :stuck_out_tongue: this site could be truly great learning resource if developers only heeded most frequent complaints and updated the lessons.