1

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?

2 Answers 2

1

Why not just import the bits you need?

Background = IRF.Background

class TowerMap extends Game
  constructor: (width, height) ->
    @background = new Background(width, height)

You should be aware that eval in EcmaScript 5 strict mode can't introduce new variable declarations so eval('var x = ...') in strict mode will not make a variable that is visible to surrounding non-eval code.

EcmaScript 5 Appendix C says

Strict mode eval code cannot instantiate variables or functions in the variable environment of the caller to eval. Instead, a new variable environment is created and that environment is used for declaration binding instantiation for the eval code (10.4.2).

Sign up to request clarification or add additional context in comments.

1 Comment

My first idea was to make it easy to require the framework, like IRF.requireClasses(). But did not get it to work, so did the eval as hacky implementation. But I guess, it's best way to just require the bits I really use, instead of everything.
1

There's no way to access local variable by name from current context (at least, in ecmascript. Maybe coffeescript has some non-standard extension).

One can access only properties of some object. Global variables could be accessed as well, cause they are properties of global object; which is window in browsers' and could be obtained as (function(){ return this })() in ecma-3.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.