如何分解此代码以减少重复(以及应该这样做)

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

本文关键字:这样做 何分解 分解 代码      更新时间:2023-09-26

我正在用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

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)作为查找表也很诱人:

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;
};

你可以用一个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;

你可以创建一个对象并用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;
};
相关文章: