3

I want to create some objects but don't know how to write the arguments of a function inside another function. Here is code with comments to explain better.

function Troop(rss, time, offense, defense){    
  this.rss= rss;
  this.time= time;
  this.offense= offense;
  this.defense= function types(a, b, c, d){ 
    this.a= a;
    this.b= b;
    this.c= c;
    this.d= d;
  } 
}
   Dwarf = new Troop(1,2,3, new types(11,22,33,44));   // this most be wrong
   alert(Dwarf.defense.a) // how can I access to the values after?

Thanks.

1 Answer 1

3

You want types to be its own function, then you can just pass in the object to the Troop constructor.

function types(a, b, c, d) {
    this.a= a;
    this.b= b;
    this.c= c;
    this.d= d;
}

function Troop(rss, time, offense, defense){    
  this.rss= rss;
  this.time= time;
  this.offense= offense;
  this.defense= defense;
}

Dwarf = new Troop(1,2,3, new types(11,22,33,44));   // these lines are right
alert(Dwarf.defense.a) // it's the function definition that was wrong :)

In general I would capitalize the class names like Types, and keep the variables like dwarf lower-case, but that's more just a question of style, not functionality.

Sign up to request clarification or add additional context in comments.

2 Comments

I thought about it, but then the last 2 lines are right? will they work?
Yep, they work just fine as you had them. I couldn't help changing the case of Types, but the only real change I made was breaking types out to a separate function. Don't define it inside of Troop. I just reverted my style suggestions so as not to muddy the issue.