0

I know that there are plenty of questions on "alternatives to eval" but so far I haven't found something corresponding to my case. I am using `CircleType.js. Basically, in my case, the user provides a string corresponding to a part of the id of the element that has the circletype effect. Then, I paste a prefix to that string. After that, I need to use this string to destroy the circletype effect.

This is what I have:

function(id) {
   var newid = "circletype" + id;
   var newid2 = eval(newid);
   newid2.destroy();
 }

This is working, but I saw that eval() is "evil" and quite controversial. Therefore, I tried some stuff, such as:

function(id) {
   var newid = {"fullid": "circletype" + id};
   newid[fullid].destroy();
 }

to follow this answer but no success. Is there an alternative to eval() in this case?

PHP Guru
  • 1,301
  • 11
  • 20
bretauv
  • 7,756
  • 2
  • 20
  • 57

1 Answers1

2

Your second example is exactly like doing this : ("circleType" + id).destroy().

In fact what you need to do is keep a reference of your CircleType instance and access it by a key. JavaScript allows you to create object literals and access its properties by using keys following this syntax:

var value = myObject['key'];

This is what the answer you mentioned tried to explain.

In your case you can implement something like this:

var circleTypes = {
    'circletypeId1': new CircleType('myElement1'), 
    'circletypeId2': new CircleType('myElement1')
};

function(id) {
   //Here Id should be equal to 'Id1' or 'Id2'
   circleTypes["circletype" + id].destroy();
}
C.Champagne
  • 5,381
  • 2
  • 23
  • 35