0

I am designing a web-based Choose Your Own Adventure game using JavaScript and jQuery, and am running into a problem with one of my functions. The basic structure is like this:

//leftSide, rightSide, thirdOption defined up here

var exampleScene = {
    sceneText: "<p>Some narrative text</p>",
    optionNames: ["Go Left", "Go Right", "A Third Option"],
    linkedScenes: [leftSide, rightSide, thirdOption]
};

function fillBox (scene) {
    $("#textBox > *").remove();
    $("#textBox").append($.parseHTML(scene.sceneText));
    promptPlayer(scene);
}

function promptPlayer (scene) {
    for (i = 0; i < scene.linkedScenes.length; i++) {
        $("#input > ol").append("<li></li>");
        $("#input > ol > li").last().text(scene.optionNames[i]);
        $("#input > ol > li").last().click(function () {
            fillBox(scene.linkedScenes[i]);
        });
    }
}

The idea is to show the text of a "Scene" object in the output area, and generate clickable options in an input area. The info for the options is drawn from the linkedScenes property of the "Scene" object. However, the reference to the linkedScene property becomes undefined when it is used as an argument in the fillBox function.

I have verified using console.log() that it is defined while in the promptPlayer function. I have also tried instead pushing scene.linkedScenes[i] into a global array and using its indices as the argument, but this also becomes undefined.

I am truly stuck here, and any help would be greatly appreciated. I am still learning JavaScript and jQuery, so any links to resources that would help clear up these sorts of issues on my own in the future would also be greatly appreciated. Thanks!

  • Looks like a duplicate to: [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – t.niese Jan 17 '16 at 17:22
  • 1
    The problem isn't the object, it's the value of `i` when the click occurs. The linked question and its answers explain why, and what to do. – T.J. Crowder Jan 17 '16 at 17:22

0 Answers0