测验应用程序的简单OO结构 - 最小化重复 - 提高OO技能

时间:2011-05-20 10:42:37

标签: javascript jquery oop

我正在制作一个简单的测验应用程序,它有多个问题。它没有后端,所有的交互都发生在一个页面上。我的对象布局如下 -

q1Choices = {
    "question": "some question",
    "resultsToRemoveIfAnswer1": [2, 4, 6],
    "resultsToRemoveIfAnswer2": [1, 3, 5]
 };
 q2Choices = {
     "question": "another question",
     "resultsToRemoveIfAnswer1": [5, 6],
     "resultsToRemoveIfAnswer2": [1, 2, 3, 4]
 };
 q3Choices = {
     "question": "a third question",
     "resultsToRemoveIfAnswer1": [3, 4],
     "resultsToRemoveIfAnswer2": [1, 2]
 };

一次出现一个问题,有两个可能的答案 - 当点击答案时,会出现另一个问题并从相应的对象中填充。

为了实现这一点,我有一个计数器变量和一个带有对象的数组

var currentQuestion = 0;

var questionArray = [q1Choices, q2Choices, q3Choices];

我可以看到这段代码中有很多重复,并且正在寻找一种更清晰,更易维护,更OO的方法。

任何人都可以给我任何指示吗?

1 个答案:

答案 0 :(得分:1)

为什么不仅使用数组?

questions = [
    [
        "some question", //question
        [2,4,6], //resultsToRemoveIfAnswer1
        [1, 3, 5] //resultsToRemoveIfAnswer2
    ],
    [
        "another question",
        [5, 6],
        [1, 2, 3, 4]
    ],
    ...
]

然后,在questions项中,您可以将question键作为索引0,resultsToRemoveIfAnswer1作为索引1,resultsToRemoveIfAnswer2作为索引2。

如果你不想依赖无意义的数字索引声明常量并使用它们

resultsToRemoveIfAnswer1 = 1
questions[0][resultsToRemoveIfAnswer1]

更多面向对象的样本:

function Questionary(){
    const question = 0
    const resultsToRemoveIfAnswer1 = 1
    const resultsToRemoveIfAnswer2 = 2
    this.questions = [
        [
            "some question",
            [2,4,6],
            [1, 3, 5]
        ],
        [
            "another question",
            [5, 6],
            [1, 2, 3, 4]
        ],
        ...
    ];
    this.currentQuestion = 0;
}

//method example
Questionary.prototype.skipQuestion = function() {
    return ++this.currentQuestion;
}

您可以更深入地添加Question对象textresultsToRemoveIfAnswer1resultsToRemoveIfAnswer2等等...