2015-04-23 81 views
6

试图保持这个简短。使用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

如果这是普通的JS,'var locations = [10];'只会声明一个包含一个元素('10')的数组,而不是一个包含10个插槽的“空”数组。 – Passerby

+4

也许你应该使用'var'来声明像'score'和'gate10'和'playerLocation'这样的变量,以便它们不是隐式的全局变量。 – jfriend00

+0

你认为这与原型有什么关系? – 2015-04-23 04:23:29

回答

4

关于变量被隐式声明:

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

playerLocation = 10; 

得分,门和playerLocation被创建为 '全球性' 的变量。 Phpstorm会提醒你注意这一点。除非它们打算全局可访问,否则用var声明变量。这将使局部变量只有在它的创建范围:

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

var playerLocation = 10; 

我建议你阅读更多关于variable scoping。如果处理不当,全局变量可能会在安全性方面留下空白。

+0

我有全局变量:var score = 0; \t var scoreField =“”; \t var playerLocation = 0; \t var inventory =“”;' -----在这种情况下完全有帮助吗,还是各个变量都有帮助? – EmeraldX

+0

我不确定你的意思。在变量前面声明var意味着它只对它声明的范围是局部的。全局变量意味着当你创建它时,变量前面没有'var'。 –