[英]New object every time I call function
I have this function to create an object: 我有此功能来创建一个对象:
function Building(owner, type, hp) {
this.owner = owner;
this.type = type;
this.hp = hp;
}
So, every time I call it, a new object is created. 因此,每次调用它时,都会创建一个新对象。
var barracks = new Building(player,bBarracks,"100");
But I have an another function which can be called several times. 但是我还有另一个可以多次调用的函数。
function build() {
if (building == 1) {
$("."+xPos+"-"+yPos).addClass("building-powerplant").addClass("taken");
hudBuildings("powerPlant"); initialize();
hudBuildings("barracks");
...
} ... }
I want to create a new object every time build() is called and give it a name of "id"+[increased number], ex. 我想在每次调用build()时创建一个新对象,并将其命名为“ id” + [增加的数字],例如。 id1, id2, ..., id10. id1,id2,...,id10。 So every time I call function, an object is created. 因此,每次我调用函数时,都会创建一个对象。 I tried increasing a number by 1 every time it is used, but I can't figure it out how to write it in. Honestly, that was kinda dumb: 每次使用时,我都尝试将数字增加1,但我不知道该如何写。老实说,这有点愚蠢:
objID++;
var id+(objID) = new Building(player,bPowPlant,"100");
Any ideas how to figure this out? 任何想法如何解决这个问题? :) :)
Could you keep the objects in an array? 您可以将对象保留在数组中吗? that way the "key" automatically sort of becomes the incremementing ID. 这样,“键”会自动成为增量ID。
so you have earlier on: 所以您早先:
var objects = [];
Then in the build function you do like 然后在构建函数中,您喜欢
objects.push(new Building(player,bPowPlant,"100"))
Then in the objects variables you will have all of the objects you have created. 然后,在对象变量中,您将拥有所有已创建的对象。 Accessible by objects[0], objects[1] etc. 可被对象[0],对象[1]等访问。
When you want to save a string as a variable name, you'll need to save it as an object key. 要将字符串另存为变量名时,需要将其另存为对象键。 You could build your own object, although a common method is to save to the window object using window[variableName]
. 尽管通常的方法是使用window[variableName]
将其保存到window对象,但是您可以构建自己的对象。 As for the id number, you can save that to a higher scoped variable and then increment inside the build()
function. 至于ID号,您可以将其保存到更高范围的变量中,然后在build()
函数中递增。
var objId = 0;
function build() {
if (building == 1) {
$("."+xPos+"-"+yPos).addClass("building-powerplant").addClass("taken");
hudBuildings("powerPlant"); initialize();
hudBuildings("barracks");
objId++;
...
} ... }
Then when you create a new object: 然后,当您创建一个新对象时:
window["id"+objId] = new Building(player,bPowPlant,"100");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.