Reputation: 4407
I have a JSON object that came from my REST service. On the server and on the front end I've declared constants that have the same name but complement each other.
They share some data, but mostly each constant has only things relevant to either the front end or back end. On the front end, what is the preferred way to map the front end constant from the back end constant?
On the backend, BuildingType
is an enum. In the JSON object below, its the first field buildingType
{buildingType: "CANNON", hp: 100, level: 1, location: Object, name: "Cannon"}
Here is the javascript code to map it to the front end version of the constant
var imageMetadata = eval("clashalytics.Images." + building.buildingType);
// In this case, the eval is the same as
var imageMetadata = clashalytics.Images.CANNON;
I'm a java developer primarily, fyi.
Upvotes: 2
Views: 1908
Reputation: 3092
First of all, you should never use: Eval()
. It has security implications
and can interfere with the scope chain. (Eval()
can access and modify a variable in its outer scope, whereas Function cannot
).
Secondly, "Javascript is a weakly typed language, which means you don’t declare variables to have a specific type beforehand". Please take a look at this website enums-in-javascript from Stijn de Witt
As a workaround you could use the Object.freeze()
, well explained on https://developer.mozilla.org
: Object.freeze()
So, your code will look like:
var Cannon = Object.freeze({"hp":100, "level":1, "location":Object, "name": "Cannon"})
And then you can access your Cannon enumerators
like a normal object: Cannon.hp
will give you 100, etc...
Please, let me know if you have any question.
Upvotes: 1
Reputation: 15351
Use array-like notation.
eval("clashalytics.Images." + building.buildingType)
is equivalent to
clashalytics.Images[building.buildingType]
You could define a getter like so
function getConst(target, path) {
return target[path];
}
and use it
getConst(clashalytics.Images, building.buildingtype)
Don't use eval needlessly!
eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension. More importantly, third party code can see the scope in which eval() was invoked, which can lead to possible attacks in ways to which the similar Function is not susceptible.
eval() is also generally slower than the alternatives, since it has to invoke the JS interpreter, while many other constructs are optimized by modern JS engines.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
Upvotes: 1