bob.setAge = setAge; - Please Explain


I still can't understand below code line.
we are using setAge method for bob object, eg bob.SetAge is fine.
But why do we assign setAge to bob.setAge. What does it mean exactly.

bob.setAge = setAge;


So we have this function set in the global namespace. However, at present only one object can use this function successfully... window.

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

Let's try running it:

 > setAge(25)
 > age
=> 25

Hey, where'd that variable age come from? The function created it on the context object, window when the assignment was made. When a property is given a value, that property is created if it does not already exist. Try this...

 > window.age
=> 25

this is the variable that stores the context object. In its present form, the function is pretty useless to a program. We rarely if ever use the window object directly. A normal program will do everything in the writer's power to protect the global space and scope all variables to functions.

Okay, so now we create a bob object:

var bob = {};

To that object we can assign a copy of the above function, making it a method of the bob object:

bob.setAge = setAge;

Notice we did not invoke the function like we did above? That is because we don't want the result of the function, but the string version of the function. If we examine the bob object we will see it there.

 > bob
=> { setAge: [Function] }

And if we wish to read the function code, we call it with its toString() method:

 > bob.setAge.toString()
=> 'function (newAge) {\n    this.age = newAge;\n}'

Lastly, we can create and assign an age property for bob.

 > bob.setAge(19)
 > bob.age
=> 19

And if we examine the object again,

 > bob
=> { setAge: [Function], age: 19 }

Starting to make sense?


Thanks. All clear now. Explained very well.


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