当我创建其他对象的 class 对象时,一个数组中的 Class 对象发生变化

Class object in one array gets changed when I create a class object of something else

为了简短起见,让例子说明一切。

我创建一个对象并打印出来(没问题),我创建更多对象(相同类型)并再次打印出第一个对象,现在显示的是最后创建的对象的数据。

然后我从另一个 class 创建一个不同的对象并再次打印出原始的第一个对象,它 returns 来自新创建的对象的数据。

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;
}

您不创建对象而只是调用函数,因此它们的 this 引用全局 (window) 对象,以便每次都覆盖那里的属性并打印出修改后的内容东西

像这样使用 new 关键字创建对象(按照惯例,您可以将 createPot 重命名为 Pot

var newObj = new createPot(mainStats.pots.types[0], 1, 1, null);
alert(newObj.name);
...