Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

trying 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
Steven Parker
216,083 Points

When 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);
}

sorry 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
Steven Parker
216,083 Points

That's right, and by itself, `${name}Action` is just a string and not a function identifier.