Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialSébastien Pennarun
4,222 Pointstrying to understand window object
I m reviewing a project that consist of two heroes attacking each other turn by turn.
in the project i came across this function:
function majData(action, casterObj, defenderObj) {
const name = action.name === 'mana' || action.name === 'shield' ? action.name : 'normal'
window[${name}Action
](action, casterObj, defenderObj)
}
can someone explain me in details what the line with the window object do?
i tryed to comment it and it seems it update the life bar and mana bar of my heroes but i cant understand what it does behind the scene.
thanks for your help,
PS: if you need the complete code just tell me
1 Answer
Steven Parker
230,853 PointsWhen posting code, use Markdown formatting, like this:
function majData(action, casterObj, defenderObj) {
const name = action.name === "mana" || action.name === "shield" ? action.name : "normal";
window[`${name}Action`](action, casterObj, defenderObj);
}
This is a clever little function that constructs another function's name by using the value in "name" attribute of the "action" object. The result will be one of these: "manaAction", "shieldAction", or "normalAction".
It then calls the function with that name and passes along the same arguments that it was given. The role of the window object here is just to allow the use of bracket notation to access the other function by name.
A more conventional way to accomplish the same thing might look like this:
function majData(action, casterObj, defenderObj) {
if (action.name == "shield") shieldAction(action, casterObj, defenderObj);
else if (action.name == "mana") manaAction(action, casterObj, defenderObj);
else normalAction(action, casterObj, defenderObj);
}
Sébastien Pennarun
4,222 PointsSébastien Pennarun
4,222 Pointssorry for the messy post and thanks for your answer. If i understand well the window object provide a "context" in order to make the function call since doing a call as follow isn't correct am i right?
`${name}Action`(action, casterObj, defenderObj)`
Steven Parker
230,853 PointsSteven Parker
230,853 PointsThat's right, and by itself, `
${name}Action
` is just a string and not a function identifier.