Я пытаюсь научиться объектно-ориентированный JavaScript и побежал в следующую проблему:Изменить глобальную переменную на основе свойства объекта
У меня есть конструктор объекта (в том, что право термин?), Как это:
function itemCreator(itemName, itemType, itemPositionX, itemPositionY) {
this.itemName = itemName;
this.itemType = itemType;
this.itemPositionX = itemPositionX;
this.itemPositionY = itemPositionY;
allItems.push(this); //store all items in a global variable
}//end itemCreator;
//then I use it to create an object
megaRocket = new itemCreator (
'megarocket',
'item_megarocket',
108,
475
)
Теперь я понял, что мне также необходимо сопоставить эти объекты, чтобы изменить различные глобальные переменные, на основе которых «itemType» имеет объект. Вот где я застрял. Как создать глобальную переменную, которая может изменять только объекты с определенным свойством itemType?
Например, я хотел бы создать объект, который увеличивает переменную с именем amountOfMegarockets, но только если itemType для этого объекта является «item_megarocket».
позже я планирую зацикливание массива этих элементов, чтобы увидеть, если объект игрока касается их (собрать элемент):
function checkForItems(){
var itemLen =allItems.length;
for (i=0; i < itemLen; i++){
var itemObject = allItems[i];
if (//checking for "collisions" here
(ship.x < (itemObject.itemBitmap.x + itemObject.size) && (ship.x + shipWidth) > itemObject.itemBitmap.x) &&
(ship.y < (itemObject.itemBitmap.y + itemObject.size) && (ship.y + shipWidth) > itemObject.itemBitmap.y)
){
itemObject.actor.y = -500; //just removing the item from canvas here (temporary solution)
// Here comes pseudo code for the part that I'm stuck with
variableBasedOnItemObject.itemType++;
}
Я надеюсь, что мое объяснение имеет смысл кому-то!
EDIT:
ответ BERĢI делает больше смысла для меня, но я не могу получить правильный синтаксис. Вот как я пытаюсь использовать код Берги в:
var amounts = {},
allItems = [];
function itemCreator(itemName, itemType, itemPositionX, itemPositionY) {
this.itemName = itemName;
this.itemType = itemType;
this.itemPositionX = itemPositionX;
this.itemPositionY = itemPositionY;
(amounts[itemType]=2); // this is different from bergi's example because I need to set the initial value of the item to two
//I also shouldn't increase the item amount on creation of the item, but only when it's specifically called from another function
this.increaseCount = amounts[itemType]++; //this should IMO increase the itemType amount inside the amounts object when called, but it doesn't seem to work
}
//creating the object the way bergi suggested:
allItems.push(new itemCreator('shootUp001', 'item_up', 108, 475));
Теперь вот проблематичная часть:
function checkForItems(){
var itemLen =allItems.length;
for (i=0; i < itemLen; i++){
var itemObject = allItems[i];
if (my condition here)
){
//code below is not increasing the value for the current itemType in the amounts object.
//Probably a simple syntax mistake?
itemObject.itemType.increaseCount;
}
}
}
Почему мой вызов itemObject.itemType.increaseCount; не увеличивая значение amounts.itemType?
ИМ, это не правильный подход в все. Вы должны разделить свою логику на разные классы, а не на один монолитный класс. –
Это не монолитный класс IMO, потому что все «элементы» очень похожи и имеют одни и те же свойства. Единственное основное различие между различными элементами - это переменная счетчика, на которую они влияют. –
Любой вопрос, начинающийся с «изменить глобальную переменную», уже задает неправильный вопрос. –