Last Updated: February 25, 2016
·
1.247K
· plugin73

CoffeeScript scope of the class

Suppose, we write class in helloworld.coffee:

class HelloWorld
  constructor: () ->
    console.log("Hello world!");</code></pre>

And we want call it in another file main.coffee:
hello = new HelloWorld()</code></pre>

The result is an error:
ReferenceError: Can not find variable: HelloWorld</code></pre>

All CoffeeScript output is wrapped in an anonymous function:  (function(){ ... })(); This safety wrapper, combined with the automatic generation of the var keyword.
Thus, our class will be compiled into the following JavaScript code:
(function(){
    var HelloWorld;
    HelloWorld = (function() {
      function HelloWorld() {
        console.log("Hello world!");
      }
      return HelloWorld;
    })();
})();</code></pre>

Obviously, our variable is visible only inside the wrapper and we must change context. For example:
class window.HelloWorld
  constructor: () ->
    console.log("Hello world!")</code></pre>

It will be compiled into the following JavaScript code:
(function(){
  window.HelloWorld = (function() {
    function HelloWorld() {
      console.log("Hello world!");
    }
    return HelloWorld;
  })();
})();</code></pre>

Now you can call this class from anywhere.<br/>
coffeescript lexical scope