0

我正试图摆脱这个错误,我的朋友和我一直遇到问题。错误在标题中,发生在第 93 行……有什么想法或建议吗?第 93 行在下面标有注释。document.body.innerHTML.replace("__ITEM__", pocket.item_name); //LINE 93

我想提的另一件事是我已经剪掉了所有不必要的代码(我认为)所以请询问您是否需要另一个部分。

如果这是一些新手错误,我不会感到惊讶,所以请随时打电话给我。对于您可能发现的任何不良做法或类似做法,我也深表歉意,我对此还是新手。

首先调用函数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);
}

像往常一样,在此先感谢并祝您编码愉快!

4

1 回答 1

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!
于 2013-10-20T01:49:00.850 回答