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 propertysetAgeto the function defined above,which is a function accepting one argument. When
susan.setAge(35);is called,thiswill refer to the caller,susan, updating her age to 35.The confusion might be from
setAgebeing used twice. Susan’s function gets defined on the left side, the right side is already defined. For example:works the same.
setAgeis also “reusable”:Demo http://jsfiddle.net/7JbKY/2/