简体   繁体   中英

Function parameter not defined - Javascript

I am programming a small text based rpg game and Ive ran into an issue that I have no clue of how to fix. The issue lies in this function and...

 function materia(mate, nam) {
      var matt = mate;
      console.log(matt);
      document.getElementById("menu").innerHTML = '<a href="#" onclick="examine(matt)">Examine ' + nam + '</a><a href="#" onclick="take(matt)">Take ' + nam + '</a><br><br><a href="#" onclick="eat(matt)">Eat/Drink ' + nam + '</a><a href="#" onclick="touch(matt)">Touch ' + nam + '</a>';
    }

This reference to the function:

var room = ['<a href="#" onclick="materia(0, \'water\')">Water</a> drips from the ceiling into <a href="#" onclick="materia(0,\'pools\')">small, murky pools</a> amongst the <a href="#" onclick="materia(1,\'stone\')"> tiles of stone</a>. The <a href="#" onclick="materia(1,\'brick walls\')">brick walls</a> are covered in <a href="#" onclick="materia(2,\'dark moss\')">dark moss</a> and seem to be slightly concave. <a href="#" onclick="materia(3,\'wood\')">Chunks of wet, termite infested wooden two by fours</a> lay on the ground.',

For some reason when i call the function examine and pass the matt variable through, it says that matt is undefined. However the console log says that matt equals 0. This all happens when I explore the dungeon until I get to the room with water in it and click the first link titled water. I have no clue whats wrong but maybe someone here does. Heres the entire code in case the issue lies somewhere else.

<html>
<body>
<p id='main'></>
<p id='menu'></p>
<p id='footer'></p>
<script>

function entity(hp, mp, body, mind, soul, name, gear, gp, statPts, lvl, xp, powers, def) {
  this.hp = hp;
  this.mp = mp;
  this.body = body;
  this.mind = mind;
  this.soul = soul; 
  this.name = name;
  this.gear = gear;
  this.gp = gp;
  this.statPts = statPts;
  this.lvl = lvl;
  this.xp = xp;
  this.powers = powers;
  this.def = def;
}

var player = new entity(5, 5, 5, 5, 5, "DJ Khaled", ["Satchel", "Linen Shirt", "Plaid Boxers", "Leather Pants"], 100, 5, 1, 0, 0, 0);
var goblin = new entity(5, 5, 2, 2, 2, "Goblin", ["Pike", "Steel Buckler", "Leather Cap", "Snakeskin Banana Hammock"], 23, 0, 1, 14, 0, 0);

function startMenu() {
  document.getElementById("main").style.textAlign = "center";
  document.getElementById("footer").style.textAlign = "center";
  document.getElementById("menu").style.textAlign = "center";
  document.getElementById("main").innerHTML ='Adventurama<br><br><a href="#" onclick="playGame()">Play</a>';
}

function playGame() {
  document.getElementById("main").innerHTML = 'Enter name:<br><input id="charName"></input><button onclick="genChar()">Enter</button>';
} 

function genChar() {
  player.name = document.getElementById("charName").value;
  genChar2();
}

function genChar2() {
  document.getElementById("main").innerHTML = player.name + ' <br>Allocate your stats:<br><br>Body ' + player.body + ' <button onclick="statAlloc(1)">+</button> <button onclick="statAllocM(1)">-</button><br><br> Mind ' + player.mind + ' <button onclick="statAlloc(2)">+</button> <button onclick="statAllocM(2)">-</button><br><br> Soul ' + player.soul + ' <button onclick="statAlloc(3)">+</button> <button onclick="statAllocM(3)">-</button><br><br> Stat Points Left: ' + player.statPts + '<br><br><button onclick="mainGame()">Continue</button>';
}

function statAlloc(a) {
  if (player.statPts <= 0) {
    genChar2();
  } else {
    switch (a) {
      case 1:
        player.body += 1;
        player.statPts -= 1;
        break;  
      case 2:
        player.mind += 1;
        player.statPts -= 1;
        break;
      case 3:
        player.soul += 1;
       player.statPts -= 1;
        break;
      }
    }
   genChar2();
}

function statAllocM(a) {
  switch (a) {
   case 1:
      player.body -= 1;
      player.statPts += 1;
      break;  
   case 2:
      player.mind -= 1;
      player.statPts += 1;
      break;
   case 3:
      player.soul -= 1;
      player.statPts += 1;
      break;
  }
  genChar2();
}

function mainGame () {
  document.getElementById("main").innerHTML = '<a href="#" onclick="dungeon(-1)">Explore the Dungeons</a><br><br><a href="#" onclick="shop()">Buy some Gear</a><br><br><a href="#" onclick="city()">Explore the City</a><br><br><a href="#" onclick="character()">View your Character</a><br><br><a href="#" onclick="inventory()">Check your Inventory</a>';
  document.getElementById("footer").innerHTML = '';
}

var prevRoom = -1;

function dungeon(z) {
  var room = ['<a href="#" onclick="materia(0, \'water\')">Water</a> drips from the ceiling into <a href="#" onclick="materia(0,\'pools\')">small, murky pools</a> amongst the <a href="#" onclick="materia(1,\'stone\')"> tiles of stone</a>. The <a href="#" onclick="materia(1,\'brick walls\')">brick walls</a> are covered in <a href="#" onclick="materia(2,\'dark moss\')">dark moss</a> and seem to be slightly concave. <a href="#" onclick="materia(3,\'wood\')">Chunks of wet, termite infested wooden two by fours</a> lay on the ground.', 
              'The <a href="#" onclick="materia(1,\'stone bricks\')"> stone bricks and tiles</a> fade away into a cave full of <a href="#" onclick="materia(4,\'stalagmites\')">stalagmites</a>. In every nook and cranny, red flickering <a href="#" onclick="materia(5,\'candles\')">red, flickering candles</a> slowly melt away. The walls are covered in noir style artwork of monstrous beasts, rape, demons, and dismembered limbs. In the center of the room there is a <a href="#" onclick="materia(1,\'stone\')">large slab of stone</a>  with a pile of bloodstained oriental robes.',
              'Cracked marble tiles crawl forward alongside giant pillars that escalate beyond the farthest reaches of your eyesight. At the end of this corridor, two giant statues of godly figures pose in an eternal state of magnificence and glory.',
              'The entirery of this room has been sculpted into a jade dragon, coiled up and sleeping. The room is fairly small only being about twelve feet in diameter. From a pinhole in the ceiling, a trail of light streams down upon a stone altar, fixed onto the floor.',
              'Long lines of wooden bookcases containing hundreds of dusty leather tomes fill the cobweb ridden stone room. Stairs on all sides of the room lead to a wooden overhang with iron rails. A red pentogram on the ceiling drips fresh blood on the wood floor.'
             ];
  do {
    var ran = Math.floor(Math.random() * room.length);
  } while (ran == prevRoom)
  prevRoom = ran;
  if (z > -1) {
    document.getElementById("main"). innerHTML = room[z];
  } else {
    document.getElementById("main"). innerHTML = room[ran];
  }
  document.getElementById("menu"). innerHTML = '';
  document.getElementById("footer").innerHTML = '<br><a href="#" onclick="dungeon()">Keep Exploring</a><br><a href="#" onclick="mainGame()">Leave</a>';

}

/* 
Actions:
  kick, punch, talk, open, 
  close, examine, take, give, 
  throw, eat, touch
Materials: 
  0: water, 1: stone, 2: moss, 3: wood
  4: stalagite, 5: candle, 6: robes
  7: marble, 8: god statue, 9: jade
  10: altar, 11: bookcase, 12: 
  13: iron rail, 14: blood, 15: debris
*/

function materia(mate, nam) {
  var matt = mate;
  document.getElementById("menu").innerHTML = '<a href="#" onclick="examine(matt)">Examine ' + nam + '</a><a href="#" onclick="take(matt)">Take ' + nam + '</a><br><br><a href="#" onclick="eat(matt)">Eat/Drink ' + nam + '</a><a href="#" onclick="touch(matt)">Touch ' + nam + '</a>';
}

function examine(mate) {  
  var exam = ['You examine the water. The water is ordinary water save for a <a href="#" onclick="materia(15,\'dirt\')">miniscule amount of debris</a> floating around.',
                       'You examin the stone. Weathered and rough and greyish blue in hue, this is some fine stone.',
                       'You examine the moss. It is fairly damp and a deep foresty green. It is very soft.',
                       'You examine the wood. It is slightly coarse and grainy, somewhat splintery around the edges. It is a tannish, sandy color.',
                       'You examine the stalagmite. Bearing the resembelance of a mineral icicle, the stalagmite is rough, ivory and pretty pointy.',
                       'You examine the candle. It is somewhat stubby with lots of buildup melted wax around the top. Protruding from the top is a black wick.',
                       'You examine the robes. They are silky and flowy and the fabric is very thin. The white hems are very large and the rest of the material is decorated with beautiful art.',
                       'You examine the marble. The marble is so smooth, you can see a faint glossy reflection of yourself in it. It is a creamy white color with faint dark swirls.',
                       'You examine the statue. A nude, godly figure of exquisite physique has been depicted from this slab of marble. It stands about 10 feet tall.'
                       ];
  document.getElementById("menu").innerHTML = exam[mate];
}

function matt() {
  var n=0;
}

startMenu();











</script>
</body>
</html>   

The problem is that matt only gets evaluated when the user clicks on the link, and then the context is no longer the function materia , but the global scope. As in that scope matt is a function (cf. end of your script), you are passing a function reference instead of the numerical value.

A quick-fix is to insert the actual value of matt in the anchor elements you insert into the dom, like this:

function materia(mate, nam) {
    var matt = mate;
    console.log(matt);
    document.getElementById("menu").innerHTML =
        '<a href="#" onclick="examine(' + matt + ')">Examine ' + nam +
        '</a><a href="#" onclick="take(' + matt + ')">Take ' + nam +
        '</a><br><br><a href="#" onclick="eat(' + matt + ')">Eat/Drink ' + nam +
        '</a><a href="#" onclick="touch(' + matt + ')">Touch ' + nam + '</a>';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM