Skip to main content

thing about Question.js

Why do I even do these things.

gist link

// Consider this a class for the Question object.
function Question(question) {
  var self = this;
  // Private variables:
  var correct = null;
  var answers = [];
  // Public Methods:
  self.getQuestion = function () {
    // This is a 'Getter' method.
    // It exposes the value of a (private) property of the object.
    // The property value cannot be changed.
    return question;
  self.getAnswers = function () {
    // Because JavaScript passes by reference, if this Getter was set up as:
    // return answers;
    // Then it would be possible to overwrite the answers array.
    // By concatenating answers onto an empty array we are actually passing
    // a copy of the answers array.
    return [].concat(answers);
  self.addAnswer = function (answer, isCorrect) {
    // Add an answer to the answers array.
    // If it exists in the array, set it as correct if it is also correct.
    var index = answers.indexOf(answer);
    if (index > -1) {
      correct = isCorrect ? index : correct;
    // Recursively call so that it can be set to correct.
    self.addAnswer(answer, isCorrect);
  self.checkAnswer = function (answer, answerIndex) {
    answerIndex = answerIndex || answers.indexOf(answer);
    return answerIndex === correct;

var question = new Question('What colours are on the flag of Switzerland?');
question.addAnswer('Black, Red and Yellow');
question.addAnswer('Red, White and Blue');
question.addAnswer('Red and White', true);
question.addAnswer('Yellow and Green');




console.log(question.checkAnswer('Black, Red and Yellow'));
console.log(question.checkAnswer('Red and White'));