Hi - I wrote some code that uses the eval function. I am in the process of rewriting the code to improve on it where possible (a learning exercise). I have read that eval is evil because of security concerns and that the eval'd code is not compiled prior to runtime.
I don't think my use of eval presents a security concern. However, I wonder if there is some way to replace the eval function with a more natural technique.
I have done this using eval(); also using a new Function method. I have tried using a window[] method but I can't get that to work.
OK, on the the actual code:
The purpose of the javascript is to count keystrokes.
I have a bunch of global counter variables declared in this fashion:
Code:
MyLib.CountQ=0;
MyLib.CountW=0;
MyLib.CountE=0;
MyLib.CountR=0;
MyLib.CountT=0;
MyLib.CountY=0;
MyLib.CountU=0;
MyLib.CountI=0;
MyLib.CountO=0;
MyLib.CountP=0;
When the Count function is called I want to update the appropriate counter. Thus: MyLib.Count'+varkeyname+'+=1; Where varkeyname is 'q' or 'w' or 'e' etc.
Code:
//MyLib is a global variable namespace.
function Count() {//updates counters
var varkeyname= specialchars(MyLib.KeyName);//identity of the key pressed.
var stra="Count"+varkeyname;// string used to change an html value.
//var strb=eval("MyLib.Count"+varkeyname+"+=1");//original eval function that worked just fine.
var strb='return MyLib.Count'+varkeyname+'+=1';//string to update a counter.
var myfunc= new Function(strb);//Function intended to replace the eval function - this also works just fine.
document.getElementById(stra).value = myfunc();
...
You can see that I have replaced the eval function with another function - but since this is also not compiled prior to runtime I don't think this is an improvement. I have read about using the window[string] method but I can't get it to work.
This is not a critical issue but I'd appreciate any comments.
Thanks, Jim