变量隐式声明和原型

时间:2015-04-23 03:08:50

标签: javascript phpstorm

试图保持这个简短。使用phpstorm查看我的代码并得到一些错误。

它说我的功能命名位置有一个"变量隐式声明"

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; 
    }
}

1 个答案:

答案 0 :(得分:4)

关于隐式声明的变量:

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

playerLocation = 10;

得分,门和玩家位置被创建为“全局”变量。 Phpstorm将提醒您这一点。除非它们是全局可访问的,否则使用var声明变量。这将使变量仅局限于创建它的范围:

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

var playerLocation = 10;

我建议您阅读有关variable scoping的更多信息。如果处理不当,全局变量可能会在您的安全性中留下空白。

相关问题