我努力学习面向对象的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++;
}
我希望我的解释是有道理的人!
编辑:
BERGI的回答最有意义给我,但我不能让语法正确。以下是我想要使用BERGI代码:
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的呼叫;不增加amount.itemType的值?
IMO,这是不正确的方法所有。你应该把你的逻辑分成不同的类,而不是单一的类。 – 2013-10-10 07:58:47
这不是一个庞然大物类IMO,因为所有的“项目”都非常相似,并且共享相同的属性。不同项目之间唯一的主要区别应该是它们影响的计数器变量。 –
任何以“修改全局变量”开头的问题都已经提出了错误的问题。 –