Get Programming with JavaScript - Listing 9.07
Listing 9.07 - A quiz question constructor
JS Bin
var QuizQuestion = function (question, answer) {
this.question = question;
this.answer = answer;
this.options = [];
this.addOption = function (option) {
this.options.push(option);
};
this.showQuestion = function () {
console.log(this.question);
this.options.forEach(function (option, i) {
console.log("(" + (i + 1) + ") " + option);
});
};
};
var question1 = new QuizQuestion(
"What is the capital of France?",
"Paris"
);
question1.addOption("Bordeaux");
question1.addOption("F");
question1.addOption("Paris");
question1.addOption("Brussels");
question1.showQuestion();
Further Adventures
Listing 9.07 - A quiz question constructor - Task 1
- Add a fifth option to question1.
var QuizQuestion = function (question, answer) {
this.question = question;
this.answer = answer;
this.options = [];
this.addOption = function (option) {
this.options.push(option);
};
this.showQuestion = function () {
console.log(this.question);
this.options.forEach(function (option, i) {
console.log("(" + (i + 1) + ") " + option);
});
};
};
var question1 = new QuizQuestion(
"What is the capital of France?",
"Paris"
);
question1.addOption("Bordeaux");
question1.addOption("F");
question1.addOption("Paris");
question1.addOption("Brussels");
question1.addOption("Lyon");
question1.showQuestion();
Listing 9.07 - A quiz question constructor - Task 2
- Create two more questions.
var QuizQuestion = function (question, answer) {
this.question = question;
this.answer = answer;
this.options = [];
this.addOption = function (option) {
this.options.push(option);
};
this.showQuestion = function () {
console.log(this.question);
this.options.forEach(function (option, i) {
console.log("(" + (i + 1) + ") " + option);
});
};
};
var question1 = new QuizQuestion(
"What is the capital of France?",
"Paris"
);
question1.addOption("Bordeaux");
question1.addOption("F");
question1.addOption("Paris");
question1.addOption("Brussels");
question1.addOption("Lyon");
// two more questions
var question2 = new QuizQuestion(
"What is the capital of Norway?",
"Oslo"
);
question2.addOption("Oslo");
question2.addOption("Stockholm");
question2.addOption("Helsinki");
question2.addOption("N");
question2.addOption("Copenhagen");
var question3 = new QuizQuestion(
"What is the capital of Peru?",
"Lima"
);
question3.addOption("Peru City");
question3.addOption("P");
question3.addOption("Lima");
[question1, question2, question3].forEach(function (q) {
q.showQuestion();
});