I'm going through a JavaScript tutorial and I'm able to complete it. But the problem is that I don't understand what one of the lines is doing.
I have a function setAge()
and then later after creating a susan
object I set one of the properties to that object as the name of the function? I don't understand why this is done. Wouldn't I be able to use the function/method without doing this?
The tutorial code:
var setAge = function (newAge) {
this.age = newAge;
};
var susan = new Object();
susan.age = 25;
susan.setAge = setAge; //how the hell does this work?
// here, update Susan's age to 35 using the method
susan.setAge(35);
It's assigning susan
's property setAge
to the function defined above,
function (newAge) {
this.age = newAge;
};
which is a function accepting one argument. When susan.setAge(35);
is called, this
will refer to the caller, susan
, updating her age to 35.
The confusion might be from setAge
being used twice. Susan's function gets defined on the left side, the right side is already defined. For example:
susan.letMyAgeBe = setAge;
susan.letMyAgeBe(35);
works the same. setAge
is also "reusable":
harry = new Object();
harry.iAmThisOld = setAge;
harry.iAmThisOld(55);
Demo http://jsfiddle.net/7JbKY/2/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With