"This" Works for Everyone



I have already figured out this assignment but one thing is unclear for me. As you can see in my code below I have to declare 'bob.SetAge', after I have already set the age. So what is the use of this 'bob.SetAge'? If you look at my code for Susan can't I just delete the 'bob.SetAge' part since I already declare it in the code below?

Thanks in advance!

// 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


In bob.steAge we are assigning the function (or method) setAge to bob ( by passing the function explicitly as a string to bob.setAge makes bob.setAge an instance of the setAge function).
Why would we need this since bob's age is already set?
We need it so that we can edit bob's age later on. If you ever want to change bob's age you now have a method to do it.
The real reason for this exercise is to illustrate that we can assign a function or a method to a variable and then this new variable points to the function just like the original variable does. This is very useful and extremely common in programming and we need to understand the concept. Most of these exercises are just that, exercises to illustrate important concepts.
Hope it helps.


I believe that we are using "bob.setAge" and stuff like that to use your "setAge" function there. Using the function will help making a new age to a person, as it had been done to Susan.


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

To what context is this function relating? The window object. Try it.

console.log(age);        // 19
console.log(window.age); // 19

We can define a context by making this function a property of a given object.

var bob = {
    age: null
bob.setAge = setAge;
console.log(bob.age);    // 21