Tor Erik Solem
Tor Erik Solem

Reputation: 13

Javascript: Using constants name as a value in an Object

Total noob here, so I might have googled with the wrong keywords. I am sorry if this has been answered a million times before.

I have a constructor function:

function CreateTeam(teamId, name, matchesPlayed, won, drawn, ...)

Giving an object some keys like: teamId, teamName, matchesPlayed, matchesWon and so on.

When calling the the constructor function I do it like this:

const argentina = new CreateTeam ('a1', 'Argentina', 0, 0, 0, ...)

I am wondering if it is possible to take the name of a constant and copy/paste it as a value of an object? In this case I would like to paste it as the second value (the value of argentina.name)

If this is possible I would be able to avoid typing the team name for every time I call the CreateTeam constructor function.

Any suggestions? Again, sorry if this has been answered before, and I just don't know the syntax well enough to search for it.

Upvotes: 1

Views: 722

Answers (2)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48600

You could set up a static/enumerable object that contains pre-defined definitions for the teams.

You could then pass one of those teams into the function, along with the general configuration. Once you have both objects, you can spread them out into a single object and unpack the properties into instance properties.

const Teams = {
  ARGENTINA : { id: 'a1', name: 'Argentina' },
  BRAZIL    : { id: 'b2', name: 'Brazil'    },
  CAMBODIA  : { id: 'c3', name: 'Cambodia'  }
};

function CreateTeam(team, config) {
  // Unpack the merged properties.
  const {
    teamId, name, matchesPlayed, wins, draws, losses
  } = { ...team, ...config };
  
  this.teamId = teamId;
  this.name = name;
  this.matchesPlayed = matchesPlayed;
  this.wins = wins;
  this.draws = draws;
  this.losses = losses;
}

CreateTeam.prototype.scoreCard = function() {
  return `${this.name} [ ${this.wins}W / ${this.draws}D / ${this.losses}L ]`
};

const argentina = new CreateTeam(Teams.ARGENTINA, {
  matchesPlayed: 10, wins: 7, draws: 1, losses: 2
});

console.log(argentina.scoreCard());

Upvotes: 1

touchmarine
touchmarine

Reputation: 2058

I didn't find any official documentation that states that it is not possible, but Stack Overflow seems to suggest that it is not. And I have never seen it before.

Look at the Variable name as a string in Javascript and JavaScript: How to get the name of constant? Stack Overflow questions, in which no anwser states that it is possible and provide "alternatives", such as using an object.

Also, even if it was possible, I would not recommend this approach as it just makes the code harder to understand. And usually, similar constructs, such as Function.name, are slow and do not work in all environments.

Upvotes: 0

Related Questions