1

I cannot understand what is bob.setAge = setAge doing. Is anybody can explain how it works?

var bob = {
    name: "Bob Smith",
    age: 15
};

var frank = {
    name: "Frank Wolf",
    age: 32
};

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

bob.setAge = setAge;
bob.setAge(23);
user3279337
  • 431
  • 1
  • 6
  • 14
  • When you use the debugger and run through the code and inspect those values before and after the debugger hits them, what do you see? – George Stocker Apr 01 '14 at 13:42

3 Answers3

6

The value of this will be determined during the time of invocation of the function. So, when you invoke it with bob like this

bob.setAge(23);

inside setAge, this will refer bob. So, 23 will be assigned to bob's age attribute.

You can dynamically attach that function to any object and invoke setAge. For example,

frank.setAge = setAge;
frank.setAge(26);

will set the age of frank to 26.

Note : If you simply invoke the setAge function without any object, like this

setAge(10);

then JavaScript will make sure that the this will refer the global object. But if you are executing this in Script mode, this will be set to undefined and setAge will fail. Because, you cannot set age on undefined.

thefourtheye
  • 206,604
  • 43
  • 412
  • 459
0

bob.setAge = setAge; ---> bob.setAge (like a reference variable) will now refer to setAge function so that you can call it like bob.setAge(23) , As you are calling it from bob object. this will refer to bob inside setAge function

Mohammad Adil
  • 43,337
  • 17
  • 86
  • 109
0

basically setAge is just a function. that suppose to alter the value of the property age.

ones you do

bob.setAge = setAge;.

you add to the object bob the method setAge that will now alter the value of bob's Age.

so now after invoking bob.setAge(23);

the age changes from 15 to 23.

Neta Meta
  • 3,720
  • 8
  • 36
  • 61