17. bob.setAge = setAge;



I am having trouble understanding the below code from exercise 17. Specifically, the code on this line:

bob.setAge = setAge;

From what I have read on other posts, we are setting the bob "setAge" property to the "setAge" method. This makes sense to me, but why would we not put a parentheses on the end like:

bob.setAge = setAge();

I thought we might do this because it is a method, but I'm also new at this so not sure about everything! Thanks! Original code below:

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

16/33 I don't understand this line: bob.setAge = setAge;

As it is written, this is a method of the global object, window. Consider,

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

In the example, this is window, the execution context.

Now in order for an object to have this method in its own context, we need to create a copy of it and assign it to that object.

bob.setAge = setAge

We do not invoke the function, only copy the .toString() form to the object.



function (newAge) {
    this.age = newAge;

Now we may set the age on the bob object.

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


Thank you mtf! That was helpful. Still a bit confusing in some parts, but overall this makes much more sense to me.


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