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
.