Captain.speak() method issue

Viewed 31

I am currently learning about objects within class. I created an object with constructor notation in Javascript, and instantiated four different objects with distinct names. For some reason, when I try to run the Captain.speak() method in my code, it doesn't work. It should display the Captain.strPhase string that I created right before initiating the command for the function. When I check this in online compilers, there are no errors, but it doesn't output my string. Would anyone happen to know why?

$(document).ready(function() {

  function Pirate(rank, phrase, id) {

    output = "";
    randNum = 1;
    secretNum = 1;

    this.strRank = rank;
    this.intNum = favnum;
    this.strPhrase = phrase;
    this.elOutput = document.getElementById(id);

    this.speak = function() {
      this.elOutput.innerHTML += "<br>" + this.strPhrase;
    }; //End speak

    this.chooseRandNum = function() {
      this.randNum = Math.floor(Math.random() * 10);
    }; //End chooseRandNum

  }; //End Pirate

  var Captain = new Pirate("Captain", "", "captain");
  var firstMate = new Pirate("First Mate", "I love guessing games!", "pirate1");
  var Quartermaster = new Pirate("Quartermaster", "This game should be fun.", "pirate2");
  var Gunner = new Pirate("Gunner", "Let's start playing!", "pirate3");

  Captain.strPhrase = "Argh maties, ready to play a guessing game?";
  Captain.speak();

}); // end of $(document).ready()
<html lang="en">

<head>

  <meta charset="utf-8">
  <!-- Begin every html page with everything up to this point (just use your own header block) -->
  <!-- Also, feel free to remove all the instructional comments as you modify this file to make it yours. -->

  <!-- This <title> displays in the page tab -->
  <title>Randomness</title>

  <!-- This will link to your CSS stylesheet for formatting as soon as you create the file. The page will work without it, though. -->
  <link rel="stylesheet" href="css/myFancyStylesheet.css">


  <!-- This links to the jQuery library so your js code will work 
         Always include this *before* your own js code (extremely important) -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


  <!-- This links to the js code specific for this page -->
  <script src="Randomness.js"></script>

</head>

<body>
  Captain's Guessing Game:

  <br></br>

  <div id="captain">
  </div>

  <br></br>

  <div id="pirate1">
  </div>

  <br></br>

  <div id="pirate2">
  </div>

  <br></br>

  <div id="pirate3">
  </div>

</body>

</html>

1 Answers

When I run your code, I get an error message:

Uncaught ReferenceError: favnum is not defined

If you comment out this line...
// this.intNum = favnum;

...everything should work just fine.

Related