Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Noob Concern: JavaScript function usage

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); 
like image 457
MonuMan5 Avatar asked Jun 09 '12 19:06

MonuMan5


1 Answers

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/

like image 137
Tina CG Hoehr Avatar answered Sep 20 '22 02:09

Tina CG Hoehr