2013-10-20 63 views
0

我想擺脫這個錯誤我的朋友和我一直有問題。錯誤在標題中,發生在第93行......任何想法或建議? 93行在下面標註了一條評論。 document.body.innerHTML.replace("__ITEM__", pocket.item_name); //LINE 93未捕獲TypeError:無法讀取屬性'item_name'的undefined

我想提到的另一件事是,我已經刪除了所有不必要的代碼(我認爲),所以請確定是否需要另一部分。

如果這是一個新手的錯誤,我不會感到驚訝,所以請隨時打電話給我。我也爲任何不良行爲道歉,或者你可能會發現,我對此仍然陌生。

函數start()被首先調用。

var status, items_none, items, pocket, money; 

function item(item_name, usage_id, description, minimum_cost) { 
    this.item_name = item_name; 
    this.usage_id = usage_id; 
    this.description = description; 
    this.worth = minimum_cost; 
    this.usage_verb = "Use"; 
    this.choose_number = false; 
}  
function start() { 
    status = "Welcome to Collector."; 

    items_none = item("---", -2, "Your pockets are empty.", 0); 
    items = new Array(); 
    items[0] = item("Cardboard Box", 0, "Open the box to see what's inside.", 100); 
    ... 

    pocket = items_none; //Start with empty pockets. 
    money = 100; //Start with 0 coins. 

    updateGui(); 
} 
function updateGui() { 
    //This updates all text on the page. 
    document.body.innerHTML.replace("__COINS__", money); 
    document.body.innerHTML.replace("__ITEM__", pocket.item_name); //LINE 93 
    document.body.innerHTML.replace("__STATUS__", status); 
    document.body.innerHTML.replace("__ITEM:USE__", pocket.usage_verb); 
    document.body.innerHTML.replace("__ITEM:DESC__", pocket.description); 
    document.body.innerHTML.replace("__ITEM:WORTH__", pocket.worth); 
    document.body.innerHTML.replace("__ITEM:VERB__", pocket.usage_verb); 
} 

像往常一樣,在此先感謝和快樂的編碼!

+3

哪條線是93線?你的樣本中沒有93行。 –

+0

@EricBrown我用評論標記了它。 'document.body.innerHTML.replace(「__ ITEM__」,pocket.item_name); //線93' – Chris

回答

3

每次添加new之前item,例如,

items_none = new item("---", -2, "Your pockets are empty.", 0); 
... 
items[0] = new item("Cardboard Box", 0, "Open the box to see what's inside.", 100); 

這是爲什麼?考慮一個名爲pair功能:

function pair(x, y) { this.x = x; this.y = y; } 

只是稱它沒有new意味着你是一個簡單的函數調用。 this只是指當前的對象上下文,可能是window

p = pair(55, 66); 
alert(window.x == 55); // true! 
alert(p.x); // error--p is undefined. 

'new'需要一個函數並將其視爲構造函數。 this設置爲新對象。

p = new pair(55, 66); 
alert(window.x == 55); // false! 
alert(p.x); // 55! 
+0

啊,知道這將是那些愚蠢的錯誤之一。謝謝,感謝!爲你+1以及接受的答案。 – Chris

+0

感謝您的補充說明。真的有幫助! – Chris

相關問題