0

I am trying to create a javascript game in which a player object has a bag/inventory with a set number of slots (similar to a Minecraft hotbar). To do this, I am trying to create an array, or new object, inside of my Player class. I imagine I could access each slot like the following:

player.inventory.slot_1 = "stick"; OR player.inventory[1] = "stick";

Where I could store each item as either an ID or string. However, doing so has not worked for me. Here is what I have attempted:

class Player {

    constructor() {

        // Player inventory
        let inventory = {

            slot_1 : null,
            slot_2 : null,
            slot_3 : null,
            slot_4 : null,
            slot_5 : null,

            offhand : null,

            armor : null
        }

        console.log("Player constructed!");

    }

}

But VSCode tells me that the inventory object is "declared but its value is never read.ts(6133)". If I try to use the structure, I get the following error: engine.player.js:36 Uncaught TypeError: Cannot read property 'slot_1' of undefined

How can I work around this, or reproduce the effect?

Bubbly
  • 301
  • 3
  • 11
  • [Duplicate](//google.com/search?q=site%3Astackoverflow.com+js+difference+variable+property) of [var vs this in Javascript object](/q/4946625/4642212). Granted, you use `let` and `class` instead of `var` and `function`, but the principle is the same. – Sebastian Simon Jul 19 '21 at 00:37

1 Answers1

1

You need to define inventory in the Player constructor onto the this property

class Player {

    constructor() {

        // Player inventory
        this.inventory = {

            slot_1 : null,
            slot_2 : null,
            slot_3 : null,
            slot_4 : null,
            slot_5 : null,

            offhand : null,

            armor : null
        }

        console.log("Player constructed!");

    }

}

Then it should be accessible on a player instance

let player = new Player();
player.inventory.slot_1 = "stick";
b.stevens.photo
  • 876
  • 2
  • 9
  • 18
  • Anytime! Would highly recommend reading up on the this keyword its basically a secret weapon https://www.javascripttutorial.net/javascript-this/ – b.stevens.photo Jul 19 '21 at 00:15
  • An exhaustive explanation of how `this` works, is here: [How does the “this” keyword work?](/q/3127429/4642212). – Sebastian Simon Jul 19 '21 at 00:40