当我创建其他类的对象时,一个数组中的类对象会被更改

时间:2016-08-16 11:23:57

标签: javascript javascript-objects

为了保持简短,让这个例子说明一切。

我创建了一个对象并将其打印出来(没关系),我创建了更多的对象(相同类型)并再次打印出第一个对象,现在它显示了最后创建的对象的数据。

然后我从另一个类创建一个不同的对象,再次打印原始的第一个对象,并从新创建的对象返回数据。

JSFiddle

var uiElements = [];
uiElements.borders = [];
uiElements.buttons = [];
uiElements.text = [];

var mainStats = [];
mainStats.money = 0;
mainStats.pots = [];
mainStats.herbs = [];

var xOffSet = 10;
var yOffSet = 10;

$(document).ready(function() {

    createUI();

});

function createUI()
{

    mainStats.herbs.types = [];
    mainStats.herbs.types[0] = "Blue";
    mainStats.herbs.types[1] = "Blood vine";
    mainStats.herbs.types[2] = "Heg flower";
    mainStats.herbs[mainStats.herbs.types[0]] = createHerb(mainStats.herbs.types[0], "herb", 60, 0.2, 10, "Basic blue herb", 1, true);

  //CORRECT
    alert(mainStats.herbs[mainStats.herbs.types[0]].name +" "+ mainStats.herbs[mainStats.herbs.types[0]].tier)

    mainStats.herbs[mainStats.herbs.types[1]] = createHerb(mainStats.herbs.types[1], "herb", 200, 0.4, 40, "Blood red tree vine", 1, true);
    mainStats.herbs[mainStats.herbs.types[2]] = createHerb(mainStats.herbs.types[2], "herb", 390.4, 0.2, 202.5, "Crescent shape flower", 1, true);

    mainStats.herbs.types[3] = "Black rose";
    mainStats.herbs[mainStats.herbs.types[3]] = createHerb(mainStats.herbs.types[3], "herb", 60, 0.2, 10, "Very dark rose", 2, true);

    mainStats.pots.types = [];
    mainStats.pots.types[0] = "Earthen";
    //mainStats.pots[mainStats.pots.types[0]] = [];
    //mainStats.pots[mainStats.pots.types[0]].color = "#654321";

//WRONG
    alert(mainStats.herbs[mainStats.herbs.types[0]].name +" "+ mainStats.herbs[mainStats.herbs.types[0]].tier)

  createPot(mainStats.pots.types[0], 1, 1, null);

//VERY WRONG
    alert(mainStats.herbs[mainStats.herbs.types[0]].name +" "+ mainStats.herbs[mainStats.herbs.types[0]].tier)

}

function createPot(name, tier, growthAccelerator, herb)
{
    this.name = name;
    this.tier = tier;
    this.growthAccelerator = growthAccelerator;
    this.herb = herb;
    this.timeLeft = 0;

    return this;
}

function createHerb(name, type, timeToBloom, seedsReturned, salesPrice, description, tier, enabled)
{
    this.name = name;
    this.type = type;
    this.timeToBloom = timeToBloom;
    this.seedsReturned = seedsReturned;
    this.salesPrice = salesPrice;
    this.description = description;
    this.tier = tier;
    this.enabled = enabled;

    return this;
}

function rx(num)
{
    return num+xOffSet;
}

function ry(num)
{
    return num+xOffSet;
}

0 个答案:

没有答案