我有一个如下定义的机器人类。但由于某种原因,processCommand 函数出现错误,我无法弄清楚它是什么。它是唯一接受参数的函数,所以我想知道我在 readCommands 函数中传递它的方式是否有问题?
任何帮助或意见表示赞赏!
function Robot(pos){
this.pos = pos;
this.language;
this.printCoords = function(){}
this.setLanguage = function() {}
this.setPos = function() {}
this.processCommand = function(s){
var direction = this.pos[2];
direction = direction.replace(" ", "");
if( (s.match('V') && this.language.match("svenska")) ||
(s.match('L') && this.language.match("engelska")) ){
switch(direction){
case "N":
// Look West
this.pos[2] = " W";
break;
case "E":
// Look North
this.pos[2] = " N";
break;
case "S":
// Look East
this.pos[2] = " E";
break;
case "W":
// Look South
this.pos[2] = " S";
break;
default:
break;
}
}
else if( (s.match('H') && this.language.match("svenska")) ||
(s.match('R') && this.language.match("engelska")) ){
switch(direction){
case "N":
// Look East
this.pos[2] = " E";
break;
case "E":
// Look South
this.pos[2] = " S";
break;
case "S":
// Look West
this.pos[2] = " W";
break;
case "W":
// Look North
this.pos[2] = " N";
break;
default:
break;
}
}
else if( (s.match('G') && this.language.match("svenska")) ||
(s.match('F') && this.language.match("engelska"))){
switch(direction){
case "N":
// Walk North
this.pos[1] += 1;
break;
case "E":
// Walk East
this.pos[0] += 1;
break;
case "S":
// Walk South
this.pos[1] -= 1;
break;
case "W":
// Walk West
this.pos[0] -= 1;
break;
default:
break;
}
}
this.printCoords();
}
this.readCommands = function() {
document.getElementById("textField").onkeyup = function(key){
key = window.event;
keyCode = key.keyCode || key.which;
if(keyCode == '13'){
var commandString = document.getElementById("textField").value;
for(var i = 0; i < commandString.length; i++){
this.processCommand(commandString[i]);
}
}
}
}
}