我是一个有用的助手,将为您进行文本翻译。
我正在尝试学习面向对象的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的调用没有增加amounts.itemType的值?