I was experimenting recently with the eval()
command while trying to come up with a new convention for a new project.
What I wanted was this: I liked the idea of having private, public, and privileged methods, ala. Doug Crockford's article, but I wanted to be able to expose public methods/variables at the TOP of my classes instead of at the bottom as is usual.
Consider this:
var Singleton = function() {
// Private
function _one() {
// code...
}
function _two() {
// code...
}
// Public
return {
one: _one,
two: _two
};
}();
With three eval()
's (two nested inside of the main one) I was able to have this syntax:
var Singleton = function() {
// Public
var $interface = {
one: $forward,
two: $forward
};
// Private
function _one() {
// code...
}
function _two() {
// code...
}
// This does the magic
return eval($init);
}('Singleton');
And against all odds and common-sense it did work. (Note that I also wanted a way to debug my namespaces which is why you can see a string passed to the singleton. $init
took care of this too.)
Anyway, I guess the point of typing all this is to say that eval()
isn't necessarily the diseased runt of the JavaScript litter that should be avoided at all costs, and can be used in more ways than just on (trusted!) code sent from a server and JSON de-serializing.
(Although in my case it ended up as a mental-workout, as I had since convinced myself not to bother with private-methods/variables after all and just use a strict namespacing convention.)