我已经将此代码作为示例来创建基本的JavaScript测验:
var Question = function(id, text, correct, incorrect) {
this.id = id;
this.text = text;
this.correct = correct;
this.isCorrectlyAnswered = false;
this.all = incorrect;
this.all.push(correct);
this.all.sort(randomSort);
}
Question.prototype.write = function() {
var qu = document.getElementById("questions");
qu.innerHTML += "<p>"+this.text+"</p>";
var questionList = "<ul class='questionlist'>";
for (var i=0; i<this.all.length; i++) {
if ( this.all[i] == this.correct ) {
questionList += "<li><label onclick='right("+this.id+")'><input type='radio' name='"+this.id+"'>"+this.all[i]+"</input></label></li>";
} else {
questionList += "<li><label onclick='wrong("+this.id+")'><input type='radio' name='"+this.id+"'>"+this.all[i]+"</input></label></li>";
}
}
questionList += "</ul>";
qu.innerHTML += questionList;
}
我对此感到困惑。任何人都可以帮助我将代码分解为“可理解的”块吗?
答案 0 :(得分:1)
该代码定义了一个用于面向对象编程的Javascript类。你可以说
var q = new Question(.......);
使用合适的参数,并调用函数
q.write();
你可以阅读更多关于OOP在(JS)http://mckoss.com/jscript/object.htm
工作的(略微奇怪的)方式