17. "This" Works for Everyone


Hi, I have a hard time understanding how the code works. I already passed the lesson, but just need help comprehending it.

var setAge = function (newAge) {
this.age = newAge;
// now we make bob
var bob = new Object();
bob.age = 30;
bob.setAge = setAge;

How does the "this.age = newAge" work, and when you call bob.setAge = setAge how does that work?



setAge() is a globally scoped method with only one context, window.

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

Now add a couple of lines to see what happens. Currently we have no object with a defined age property.


console.log(age);          // 19

What? Where did that come from? Answer: the global object, window.

console.log(window.age)    // 19

But this is not much use to us, is it? The method is, though, especially given that it has an exposed this variable that permits it to be associated with any object, not just window.

When we write,

bob.setAge = setAge;

We are not invoking the function, but instead we are copying its toString() form. If we examine the bob object we will see that it now has a setAge() method of its own.

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

Now the method can be invoked on the bob object,


console.log(bob.age);    // 20

We can repeat this with any number of objects.


Thank you for the help!


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