1

I'm building a website with some rpg stat blocks for a table top role playing game I'm trying get a string element to use data from another element. but it when I go to boot up a web browser it prints it as undefined.

These element are part of the same object.

        str: 18,
        proficiency: 2,
        attackroll: "",
        Attack: function() {
            this.attackroll = ((this.proficiency + Math.floor(((this.str)-10)/2)).toString());
            console.log(this.attackroll)
        },
actions:"Bite. +" + this.attackroll +  " to hit, reach 5ft, one target. Hit: 16 (3d8 + 4 piercing damage).",

When I go to run the HTML it prints:

Bite. +undefined to hit, reach 5ft, one target. Hit: 16 (3d8 + 4 piercing damage).

  • Please provide enough code so others can better understand or reproduce the problem. – Community Feb 28 '23 at 19:41
  • 1
    can't really see what is going on (can't see how you are using the object) - but looks like the `Attack` property was never called to trigger setting the `attackroll` property. – chaimm Feb 28 '23 at 19:51
  • Does this answer your question? ["this" inside object](https://stackoverflow.com/questions/7043509/this-inside-object) – nullromo Mar 01 '23 at 00:46
  • [This answer](https://stackoverflow.com/a/7043822/4476484) might help you. `this` doesn't really work with objects like how you're trying to use it. You could use a `class` instead or try building the object up over multiple steps. – nullromo Mar 01 '23 at 00:47

1 Answers1

0

You could use a class for this.

class Character {
    constructor(str, proficiency) {
        this.str = str;
        this.proficiency = proficiency;
        this.attackroll = ((this.proficiency + Math.floor(((this.str)-10)/2)).toString());
        this.actions = "Bite. +" + this.attackroll +  " to hit, reach 5ft, one target. Hit: 16 (3d8 + 4 piercing damage).";
    }
    
    Attack() {
        console.log(this.attackroll)
    }
}

Create a new instance of the class like this:

const myCharacter = new Character(18, 2);

and then you can access the attributes and call the functions like this:

myCharacter.actions
myCharacter.Attack();

Code snippet

You can run this and see it working:

class Character {
    constructor(str, proficiency) {
        this.str = str;
        this.proficiency = proficiency;
        this.attackroll = ((this.proficiency + Math.floor(((this.str)-10)/2)).toString());
        this.actions = "Bite. +" + this.attackroll +  " to hit, reach 5ft, one target. Hit: 16 (3d8 + 4 piercing damage).";
    }
    
    Attack() {
        console.log(this.attackroll)
    }
}

const myCharacter = new Character(18, 2);

console.log(myCharacter.str);
console.log(myCharacter.proficiency);
console.log(myCharacter.attackroll);
console.log(myCharacter.actions);
myCharacter.Attack();
nullromo
  • 2,165
  • 2
  • 18
  • 39