首页 > 其他 > 详细

面向对象编程

时间:2015-07-09 10:57:45      阅读:185      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!