javascript - 如何调试 JavaScript 对象问题?

标签 javascript debugging

我正在经历这个JavaScript tutorial遇到了一个问题,我希望有人能帮助我。选择测验的最后一个问题后,我的 showScore() 函数将结果显示为“未定义”。通过进一步调试,我发现这是我的quiz对象的问题。在我的 PopulateQuestion() 函数中,我能够在执行 showScore() 函数之前打印出测验对象。但是,当我尝试从 showScore() 函数中打印出测验对象时,它返回未定义。

我想提高调试此类问题的能力。根据我到目前为止所做的调试,我有根据的猜测是这是一个范围问题,但我被卡住了。有没有人对进一步调试有任何建议?

这是我的代码

Index.html

 <!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>JS Quiz</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="main.css">
  </head>
  <body>
    <div class="quiz-container">
      <div id="quiz">
        <h1>Star Wars Quiz</h1>
        <hr style="margin-top: 20px;" />
        <p id="question">Who is Darth Vader?</p>
        <div class="buttons">
          <button id="b0"><span id="c0"></span></button>
          <button id="b1"><span id="c1"></span></button>
          <button id="b2"><span id="c2"></span></button>
          <button id="b3"><span id="c3"></span></button>
        </div>
        <hr style="margin-top: 50px" />
        <footer>
          <p id="progress">Question x of n</p>
        </footer>
      </div>
    </div>
    <script src="quiz-controller.js"></script>
    <script src="question.js"></script>
    <script src="app.js"></script>
  </body>
</html>

app.js

function populateQuestion() {
  if(quiz.isEnded()) {
    // display score
    console.log(quiz);
    showScore();
  } else {
    // display question
    var qElement = document.getElementById('question');
    qElement.innerHTML = quiz.getCurrentQuestion().text;

    // display choices
    var choices = quiz.getCurrentQuestion().choices;
    for(var i = 0; i < choices.length; i++) {
      var choice = document.getElementById('c' + i);
      choice.innerHTML = choices[i];
      guess("b" + i, choices[i]);
    }
    showProgress();
  }
}

function guess(id, guess) {
    var button = document.getElementById(id);
    button.onclick = function() {
      quiz.guess(guess);
      populateQuestion();
    };
}

function showProgress() {
    var currentQuestionNum = quiz.questionIndex + 1;
    var progress = document.getElementById("progress");
    progress.innerHTML = "Question " + currentQuestionNum + " of " + quiz.questions.length;
}

function showScore() {
  console.log(quiz);
  var resultsHTML = "<h1>Results</h1>";
  resultsHTML += "<h2 id='score'>Your Score: " + quiz.getScore() + "</h2>";
  var quiz = document.getElementById("quiz");
  quiz.innerHTML = resultsHTML;
}

var questions = [
  new Question("Who is Darth Vader?",
  ["Luke Skywalker", "Anakin Skywalker", "Your Mom", "Your Dad"],
  "Anakin Skywalker"),
  new Question("What is the name of the third episode?",
  ["Return of the Jedi", "Revenge of the Sith", "A New Hope", "The Empire Strikes Back"],
  "Revenge of the Sith"),
  new Question("Who is Anakin Skywalker's son?",
  ["Luke Skywalker", "Anakin Skywalker", "Your Mom", "Your Dad"],
  "Luke Skywalker"),
  new Question("What is the name of the sixth episode?",
  ["Return of the Jedi", "Revenge of the Sith", "A New Hope", "The Empire Strikes Back"],
  "Return of the Jedi")
];

var quiz = new Quiz(questions);
populateQuestion();

question.js

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

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

quiz-controller.js

function Quiz(questions) {
  this.score = 0;
  this.questionIndex = 0;
  this.questions = questions;
}

Quiz.prototype.getScore = function() {
    return this.score;
};

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

Quiz.prototype.isEnded = function() {
  return this.questionIndex === this.questions.length;
};

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

  this.questionIndex++;
};

最佳答案

您的问题是您在 showScore() 函数中定义了一个名为 quiz 的局部变量。这个局部变量隐藏了同名的全局变量(即使它是在代码后面定义的)。

您可以通过重命名 showScore 中的局部变量轻松解决此问题(下面显示为 q 而不是 quiz):

function populateQuestion() {
  if(quiz.isEnded()) {
    // display score
    console.log(quiz);
    showScore();
  } else {
    // display question
    var qElement = document.getElementById('question');
    qElement.innerHTML = quiz.getCurrentQuestion().text;

    // display choices
    var choices = quiz.getCurrentQuestion().choices;
    for(var i = 0; i < choices.length; i++) {
      var choice = document.getElementById('c' + i);
      choice.innerHTML = choices[i];
      guess("b" + i, choices[i]);
    }
    showProgress();
  }
}

function guess(id, guess) {
    var button = document.getElementById(id);
    button.onclick = function() {
      quiz.guess(guess);
      populateQuestion();
    };
}

function showProgress() {
    var currentQuestionNum = quiz.questionIndex + 1;
    var progress = document.getElementById("progress");
    progress.innerHTML = "Question " + currentQuestionNum + " of " + quiz.questions.length;
}

function showScore() {
  console.log(quiz);
  var resultsHTML = "<h1>Results</h1>";
  resultsHTML += "<h2 id='score'>Your Score: " + quiz.getScore() + "</h2>";
  var q = document.getElementById("quiz");
  q.innerHTML = resultsHTML;
}

var questions = [
  new Question("Who is Darth Vader?",
  ["Luke Skywalker", "Anakin Skywalker", "Your Mom", "Your Dad"],
  "Anakin Skywalker"),
  new Question("What is the name of the third episode?",
  ["Return of the Jedi", "Revenge of the Sith", "A New Hope", "The Empire Strikes Back"],
  "Revenge of the Sith"),
  new Question("Who is Anakin Skywalker's son?",
  ["Luke Skywalker", "Anakin Skywalker", "Your Mom", "Your Dad"],
  "Luke Skywalker"),
  new Question("What is the name of the sixth episode?",
  ["Return of the Jedi", "Revenge of the Sith", "A New Hope", "The Empire Strikes Back"],
  "Return of the Jedi")
];

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

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

function Quiz(questions) {
  this.score = 0;
  this.questionIndex = 0;
  this.questions = questions;
}

Quiz.prototype.getScore = function() {
    return this.score;
};

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

Quiz.prototype.isEnded = function() {
  return this.questionIndex === this.questions.length;
};

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

  this.questionIndex++;
};

var quiz = new Quiz(questions);
populateQuestion();
 <!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>JS Quiz</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="main.css">
  </head>
  <body>
    <div class="quiz-container">
      <div id="quiz">
        <h1>Star Wars Quiz</h1>
        <hr style="margin-top: 20px;" />
        <p id="question">Who is Darth Vader?</p>
        <div class="buttons">
          <button id="b0"><span id="c0"></span></button>
          <button id="b1"><span id="c1"></span></button>
          <button id="b2"><span id="c2"></span></button>
          <button id="b3"><span id="c3"></span></button>
        </div>
        <hr style="margin-top: 50px" />
        <footer>
          <p id="progress">Question x of n</p>
        </footer>
      </div>
    </div>
    <script src="quiz-controller.js"></script>
    <script src="question.js"></script>
    <script src="app.js"></script>
  </body>
</html>

关于javascript - 如何调试 JavaScript 对象问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51679524/

相关文章:

ajax - 如何解决 Ajax 请求时 Firebug 的 “Aborted” 消息?

javascript - 在 javascript/typescript 中向 Date 添加天数会给出完全错误的日期

ios - 存折优惠券无法在safari中打开

javascript - 为什么 Phantomjs 不能在该网站上使用?

javascript - HTML5 视频播放完毕后是否已将自身重置为开始?

debugging - Debug模式下的自由半径错误

debugging - 无法调试 Blazor WebAssembly

javascript - JavaScript 中如何获取调用函数的行?

javascript - 使用 AJAX 传递变量并在其他页面上使用它

javascript - 使用 JavaScript 或 jQuery 更改 CSS 规则