I want to improve a small framework, and therefore I want to get rid of two calls to eval.
Let the code speak:
# irf.coffee (The Framework)
# Classes which are appended to the namespace 'IRF'
classes = [
"Background"
"BoundingBox"
# ...
]
# Namespace where to attach classes
@IRF = {}
# TODO: Get rid of eval(c)
for c in classes
@IRF[c] = eval(c)
I only want the IRF to ‘pollute’ the global namespace so I could access classes/objects like new IRF.Background().
The goal of this framework is to be used by other projects including this framework.
So I might have a project like this:
class TowerMap extends IRF.Game
constructor: (width, height) ->
@background = new IRF.Background(width, height)
As you see, I have to use the IRF namespace here, but within this particular project I’d like to use it without the namespace, as I did this:
# Require all Class of IRF, so we won't need namespace here
# TODO: get rid of eval
eval("var #{k} = v") for k,v of IRF
class TowerMap extends Game
constructor: (width, height) ->
@background = new Background(width, height)
Everything works as expected, but somehow those two evals disturb me.
Might there be another solution?
Why not just import the bits you need?
You should be aware that
evalin EcmaScript 5 strict mode can’t introduce new variable declarations soeval('var x = ...')in strict mode will not make a variable that is visible to surrounding non-eval code.EcmaScript 5 Appendix C says