我正在製作一個HTML5遊戲,併爲它考慮15個關卡。我有一個包含關卡對象的關卡類。這是它的代碼部分。JavaScript原型:一個有趣的對象沒有方法錯誤
function levels(){
this.allLevels=[];
for (var i = 1; i <=15; i++) {
this.allLevels[this.allLevels.length]=new level(); //LEVEL OBJECTS CREATED INTO OBJECT
this.allLevels[this.allLevels.length-1].levelNumber=i; //LEVEL NUMBERS ARE SET
(i==1)? this.allLevels[this.allLevels.length-1].state='ZERO':this.allLevels[this.allLevels.length-1].state='LOCKED'; //LEVEL STATES ARE SET
}
}
正如你可能看到的,我有一個allLevels數組來保存關卡信息。到目前爲止,一切都很好。在創建這個類之後,我添加了init併爲這個類添加了方法。這裏是;
levels.prototype.initAll = function(){
for(var i=0;i<=15;i++){
this.allLevels[i].initAllCoor();
}
};
levels.prototype.draw=function(){
this.cleanCanvas();
for(var i=0;i<=15;i++){
this.allLevels[i].drawLevelIcon();
}
};
levels.prototype.cleanCanvas=function(){
ctxCanvasLevels.clearRect(0,0,800,570);
};
它現在只有三種方法。您看到的函數(initAllCoor和drawLevelIcon)是級別對象的方法。當我調用這些方法時,一切正常。
你可以說,如果一切正常,你在問什麼。儘管一切運行正常,但我在Chrome的控制檯上出現錯誤。
Uncaught TypeError: Cannot call method 'initAllCoor' of undefined
Uncaught TypeError: Cannot call method 'drawLevelIcon' of undefined
我不明白,它說「不能呼叫」,但它確實如此。由於這個錯誤,我也無法使用console.log函數。
「不能稱之爲」在這裏的意思更具體的「關於'不能訪問任何財產undefined'「 – Bergi
你應該從'i = 0'到'14'創建(並迭代)15個級別。 – Bergi
這是有效的。現在沒有錯誤:) –