You want to use the eval()
function. But what you show above would not create a property on the fn
variable. It instead just creates a function that you are assigning to fn
. If you want to create an object with the property say
try this instead:
var fn = eval('({ say: function (something) { alert(something); }})');
This evaluates the expression that resolves to the object containing a property named say
. This properties value is a function that can be called like what you described above:
fn.say('hello');
Also, despite all the flak that eval()
gets, there are actually some uses for it.
- JSON conversions
- moving definitions between namespaces
- minimization and obfuscation of JavaScript code
- dynamic code rewriting and injection
- creating metalanguages
As far as the security concerns, eval()
itself does not add any tangible vulnerability to your code. Unless you are doing something grossly irresponsible (such as calling eval()
on user input), there is nothing that eval introduces by its presence that wouldn't be a concern anyway. The argument often given is the security threat when evaluating content returned from the server. This threat assumes that we can't even trust the server, in which case we probably have bigger issues. Another often used argument is the man-in-the-middle attack, where someone is injecting malicious content into our resource request. Once again, if this is happening we probably have bigger concerns. If the attacker has the ability to inject malicious content into the servers response, then there is nothing preventing them from:
- returning attacker-controlled code for JavaScript loaded via <script
src="">
- returning attacker-controlled code for JSON-P requests.
- stealing cookies and user data without altering anything
- returning attacker-controlled HTML and CSS used for phishing
The bottom line is that often the security threat arguments made for not using eval()
are threats that will be problematic regardless of whether or not your code uses eval()
. Despite what others might say, eval()
is just another tool in the toolbox. Don't use it carelessly, or where another piece of code might do better. But don't disregard it entirely, even if Douglas Crockford tells you to.
Hope this helps!
References:
Secrets of the JavaScript Ninja
eval() isn't evil, just misunderstood