我努力學習面向對象的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,因爲所有的「項目」都非常相似,並且共享相同的屬性。不同項目之間唯一的主要區別應該是它們影響的計數器變量。 –
任何以「修改全局變量」開頭的問題都已經提出了錯誤的問題。 –