变量隐式声明和原型

Variable Implicitly Declared and Prototypes

尽量保持简短。使用 phpstorm 查看我的代码,发现了一些错误。

它说我的函数命名位置有一个 "Variable Implicitly Declared"

function towngate10() {
    updateDisplay(locations[10].description);
    if (!gate10) {
        score = score+5;
        gate10 = true;
    }
    playerLocation = 10;
    displayScore();
    document.getElementById("goNorth").disabled=true;
    document.getElementById("goSouth").disabled=false;
    document.getElementById("goEast").disabled=true;
    document.getElementById("goWest").disabled=true;
}

此外,我只是想确保我正确地制作了我的原型 只是一个例子

全局数组:

var locations = [10];
locations[0] = new Location(0,"Intersection","This is where you awoke.");
locations[1] = new Location(1,"Cornfield","The cornfields expand for miles.");
locations[2] = new Location(2,"Lake","A large lake that is formed by a river flowing from the East.", new Item(1,"Fish","An old rotting fish."));
locations[3] = new Location(3,"Outside Cave","Entrance to the dark cave.");

定位函数:

function Location(id, name, description, item) {
    this.id = id;
    this.name = name;
    this.description = description;
    this.item = item;
    this.toString = function() {
        return "Location: " + this.name + " - " + this.description; 
    }
}

关于隐式声明的变量:

if (!gate10) {
    score = score+5;
    gate10 = true;
}

playerLocation = 10;

score、gate 和 playerLocation 被创建为 'global' 变量。 Phpstorm 会提醒你这一点。除非它们旨在全局访问,否则请使用 var 声明变量。这将使变量仅在创建它的范围内局部化:

if (!gate10) {
    var score = score+5;
    var gate10 = true;
}

var playerLocation = 10;

我建议您阅读更多有关 variable scoping 的内容。如果处理不当,全局变量可能会在您的安全中留下漏洞。