函数内部函数的参数

时间:2015-04-22 18:49:36

标签: javascript jquery

我想创建一些对象,但不知道如何在另一个函数内编写函数的参数。这是带有注释的代码,可以更好地解释。

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?

感谢。

1 个答案:

答案 0 :(得分:3)

您希望types成为自己的函数,然后您可以将对象传递给Troop构造函数。

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 :)

一般来说,我会像Types那样大写类名,并保持像dwarf这样的变量小写,但这更像是一个风格而不是功能的问题。