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
Written by Alexander Vagin
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Coffescript
Authors
Related Tags
#coffescript
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#