如何提取此代码以减少重复(并且应该这样做)?

How can this code be factored out to reduce duplication (and should it)?

我正在 javascript 制作一款基于浏览器的基本游戏。这是我对可玩角色的控制方法:

obj.update = function(){
        if (this.keyPressed === 'right'){
            this.x += 100;
        }
        if (this.keyPressed === 'left'){
            this.x += -100;
        }
        if (this.keyPressed === 'up'){
            this.y -= 100;
        }
        if (this.keyPressed === 'down'){
            this.y -= -100;
        }
        // reset key press
        this.keyPressed = null;
    };

我意识到我在这里重复了代码。我应该把重复的元素分解掉吗?如果是这样,最好的方法是什么?

您可以使用 switch 语句使其更具可读性:

switch (this.keyPressed) {
    case 'right': this.x += 100;  break;
    case 'left' : this.x += -100; break;
    case 'up'   : this.y -= 100;  break;
    case 'down' : this.y -= -100; break;
}
this.keyPressed = null;

该不该见仁见智。回答 can 部分,我可能会使用 switch:

obj.update = function(){
    switch (this.keyPressed) {
        case 'right':
            this.x += 100;
            break;
        case 'left':
            this.x += -100;
            break;
        case 'up':
            this.y -= 100;
            break;
        case 'down':
            this.y -= -100;
            break;
    }
    // reset key press
    this.keyPressed = null;
};

...并且可能使 100 成为常量(在 ES2015/ES6 中)或我没有更改的变量(在 ES5 和更早版本中)。

尽管使用对象(或 ES2015/ES6 中的 Map)作为查找也很诱人 table:

var table = {
    right: {x:  100, y:    0},
    left:  {x: -100, y:    0},
    up:    {x:    0, y: -100},
    down:  {x:    0, y:  100}
};
obj.update = function(){
    var entry = table[this.keyPressed];
    if (entry) {
        this.x += entry.x;
        this.y += entry.y;
    }
    // reset key press
    this.keyPressed = null;
};

您可以创建一个对象并用 this 调用它。

此解决方案的智能部分,它对更多命令开放,例如保存状态或其他。

var op = {
    right: function (t) { t.x += 100; },
    left: function (t) { t.x -= 100; },
    up: function (t) { t.y -= 100; },
    down: function (t) { t.y += 100; }
};

obj.update = function () {
    var f = op[this.keyPressed];
    f && f(this);
    this.keyPressed = null;
};