Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arguments of function inside a function

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 Answers

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.

like image 124
Danny Avatar answered Feb 01 '26 15:02

Danny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!