I am learning about objects and their scopes, I got confused and decided to make a D&D pathfinder character sheet for practice.
I made the character sheet as an object, child objects for ability scores, strength/dexterity/intelligence/etc... and then base and modifier values.
in D&D you use your base value to calculate your modifier value and the modifier is used throughout the game. The calculation for modifier is (base - 10) / 2
as i run this i only get 0 when called console.log(characterSheet.abilityScore.strength.modifier)
I assume my confusion is about my understanding of the scope range between the function and modifier/base. but I'm not sure where to start.
const characterSheet = {
abilityScore: {
strength: {
base: 2,
modifier: 0,
calcMod: function () {
this.modifier = Math.floor((this.base - 10) / 2);
},
},
dexterity: {
base: 8,
modifier: 0,
calcMod: function () {
this.modifier = Math.floor((this.base - 10) / 2);
},
},
intelligence: {
base: 16,
modifier: 0,
calcMod: function () {
this.modifier = Math.floor((this.base - 10) / 2);
},
},
},
}
I have also tried placing the function in the global scope but always returns NaN.
const characterSheet = {
abilityScore: {
strength: {
base: 2,
modifier: function () {
return calcMod(this.base);
},
strength: {
base: 8,
modifier: function () {
return calcMod(this.base);
},
},
strength: {
base: 16,
modifier: function () {
return calcMod(this.base);
},
},
},
}};
function calcMod(val) {
return Math.floor((val - 10) / 2);
}
console.log(calcMod(characterSheet.abilityScore.strength));
CodePudding user response:
You should use
function buildScore(base) {
return {
base,
modifier: Math.floor((base - 10) / 2),
};
}
const characterSheet = {
abilityScore: {
strength: buildScore(2),
dexterity: buildScore(8),
intelligence: buildScore(16),
},
};
console.log(characterSheet.abilityScore.strength);
No methods, no problems. You could also achieve something like this with getters, but it would be much more complicated.
CodePudding user response:
you can use that... ?
const characterSheet =
{ abilityScore:
{ strength:
{ base : 2
, modifier : 0
}
, dexterity:
{ base : 8
, modifier : 0
}
, intelligence:
{ base : 16
, modifier : 0
}
, calcMod ( ability )
{
return this[ability].modifier = 0 | ((this[ability].base - 10) / 2);
} } }
console.log( characterSheet.abilityScore.calcMod( 'strength' ) )
console.log( characterSheet.abilityScore.strength.modifier )
OR:
const characterSheet =
{ abilityScore:
{ strength : { base : 2, modifier : 0 }
, dexterity : { base : 8, modifier : 0 }
, intelligence : { base : 16, modifier : 0 }
} };
function calcMod( val )
{
return val.modifier = 0 | ((val.base - 10) / 2);
}
console.log( calcMod( characterSheet.abilityScore.strength ))