Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>With a bit of foresight you can do this pretty easily <em>and</em> protect yourself against using <code>eval</code>. Keep a list somewhere of the classes that you want to instantiate by name:</p> <pre><code>class Dog bark:-&gt; "Woof" # Or window.named_classes if you need to access # `named_classes` globally (or just in another # CoffeeScript file). named_classes = { Dog: Dog } </code></pre> <p>and then use your lookup table instead of <code>eval</code>:</p> <pre><code>name = 'Dog' dog = new named_classes[name] </code></pre> <p>When you say <code>class Dog</code>, you end up with a local variable called <code>Dog</code>:</p> <pre><code>var Dog; Dog = (function() { /* ... */ })(); </code></pre> <p>and there's no way to get at a local JavaScript variable unless you store it somewhere that you can access by name. Also note that <code>eval</code> won't work if you define <code>Dog</code> in one CoffeeScript file and want to access it another, <a href="http://coffeescript.org/#lexical_scope">CoffeeScript wraps each file in self-executing anonymous function to limit variable scope</a>:</p> <blockquote> <p>all CoffeeScript output is wrapped in an anonymous function: <code>(function(){ ... })()</code>; This safety wrapper, combined with the automatic generation of the <code>var</code> keyword, make it exceedingly difficult to pollute the global namespace by accident.</p> <p>If you'd like to create top-level variables for other scripts to use, attach them as properties on <strong>window</strong>, or on the <strong>exports</strong> object in CommonJS.</p> </blockquote>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload