码迷,mamicode.com
首页 > 其他好文 > 详细

面向对象编程

时间:2015-07-09 10:59:35      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:

function Question(text,choices,answer){//question.js
	this.text=text;
	this.choices=choices;
	this.answer=answer;
}

Question.prototype.isCorrectAnswer=function(choice){
	return this.answer===choice;
}

  

function Quiz(questions){//quiz.js
	this.score=0;
	this.questions=questions;
	this.currentQuestionIndex=0;
}

Quiz.prototype.guess=function(answer){
	if(this.getCurrentQuestion().isCorrectAnswer(answer)){
		this.score++;
	}
	this.currentQuestionIndex++;
}

Quiz.prototype.getCurrentQuestion=function(){
	return this.questions[this.currentQuestionIndex];
}

Quiz.prototype.hasEnded=function(){
	return this.currentQuestionIndex>=this.questions.length;
}

  

var QuizUI={//quiz_ui.js
	displayNext:function(){
		if(quiz.hasEnded()){
			this.displayScore();
		}else{
			this.displayQuestion();
			this.displayChoices();
			this.displayProgress();
		}
	},
	displayQuestion:function(){
		this.populateIdWithHTML("question",quiz.getCurrentQuestion().text);
	},
	displayChoices:function(){
		var choices=quiz.getCurrentQuestion().choices;
		for(var i=0;i<choices.length;i++){
			this.populateIdWithHTML("choice"+i,choices[i]);
			this.guessHandler("guess"+i,choices[i]);
		}
	},
	displayScore:function(){
		var gameOverHTML="<h1>Game Over</h1>";
		gameOverHTML+="<h2>Your score is: "+quiz.score+"</h2>";
		this.populateIdWithHTML("quiz",gameOverHTML);
	},
	populateIdWithHTML:function(id,text){
		var element=document.getElementById(id);
		element.innerHTML=text;
	},
	guessHandler:function(id,guess){
		var button=document.getElementById(id);
		button.onclick=function(){
			quiz.guess(guess);
			QuizUI.displayNext();
		}
	},
	displayProgress:function(){
		var currentQuestionNumber=quiz.currentQuestionIndex+1;
		this.populateIdWithHTML("progress","Question "+currentQuestionNumber+" of "+quiz.questions.length);
	}
}

  

var questions=[//app.js
	new Question("who was the ?",["G W","T J"],"G W"),
	new Question("what is the ?",["ps","42"],"42")
];

var quiz=new Quiz(questions);

QuizUI.displayNext();

  

面向对象编程

标签:

原文地址:http://www.cnblogs.com/sunhe/p/4632299.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!