2015-04-23 86 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'。 –