Everything is inside an IIFE for data privacy and so as not to interfere with any other programmers' code - Javascript Function

Javascript examples for Function:Immediately Invoked Function Expressions IIFE

Description

Everything is inside an IIFE for data privacy and so as not to interfere with any other programmers' code

Demo Code


// :/*from   w w  w . ja va 2  s.  com*/
(function() {
  // Function Constructor for Questions:
  var Question = function(question, answers, correct) {
    this.question = question;
    this.answers = answers;
    this.correct = correct;
  };

  // Method to display the randomly selected question in the console log:
  Question.prototype.displayQuestion = function() {
    console.log(this.question);
    for (var i = 0; i < this.answers.length; i ++) {
      console.log(i + ": " + this.answers[i]);
    }
  }

  // Method to verify player's answer:
  Question.prototype.checkAnswer = function(ans, callback) {
    var sc;
    if (ans == this.correct) {
      console.log("Correct!");
      // Increase score and display it:
      sc = callback(true);
    }
    else {
      console.log("Sorry, that is incorrect.");
      // Display score but do not increase it:
      sc = callback(false);
    }
    this.displayScore(sc);
  }

  // Display score in the console:
  Question.prototype.displayScore = function(score) {
    console.log("Your current score is: " + score);
    // Separater line for viewing ease:
    console.log("---------------------");
  }

  // Questions to be passed into Function Constructor:
  var q1 = new Question("What year was JFK shot?", ["1961", "1962", "1963"], 2);
  var q2 = new Question("Where does Tucker Max hope they serve beer?", ["Heaven.", "Hell.", "His house."], 1);
  var q3 = new Question("What color is the water tower in Corcoran?", ["Red", "White", "There is no water tower in Corcoran!"], 2);

  // Array containing the questions to be passed into Function Contructor:
  var questions = [q1, q2, q3];
  // Score Counter:
  function score() {
    var sc = 0;
    return function(correct) {
      if (correct) {
        sc++;
      }
      return sc;
    }
  }

  var keepScore = score();
  

  function nextQuestion() {
    // Generate random number between 0 and 2:
    var n = Math.floor(Math.random() * questions.length);
    questions[n].displayQuestion();
    var answer = prompt("Please type the number of the correct answer. Type \"exit\" to stop.");
    if (answer !== "exit") {
      questions[n].checkAnswer(parseInt(answer), keepScore);
      nextQuestion();
    }
  }
  
  nextQuestion();
})();

Related Tutorials