This is a follow up to my previous question Javascript: ReferenceError: MyClass is not defined.
A .coffee file with this converted to .js will create a MyClass
available only inside its scope.
class MyClass
name: (name) ->
Is there a way in CoffeScript to make the class available to the outer scope? I should be able to <script src..
the file on a HTML page and instantiate the class from the console.
This stackoverflow gives a very comprehensive overview of creating global objects with coffeescript with some very good examples included.
For this example the coffeescript:
Will compile to:
Which will give the same behaviour as the answer to your previous question.
You'll "pollute the global scope" no matter how you do it. It's just a matter of how you do it.
The
@
symbol in CoffeeScript is used to mean "this scope". So you can even use it on a Class definition. The result on a class declaration is that the class is defined in the scope of thewindow
object (unless there are some other circumstances, but that's not likely in what you're describing here).However, I prefer to do this with a namespace, personally. Think about
google.maps.Map
or if you've ever written Actionscript 3:flash.display.MovieClip
.At the top of your CoffeeScript file put something along the lines of this:
Now when you create your class, you can say:
In your
document.ready
(if you're using jQuery) you'll globally have access to that namespace and all its classes.Example:
Make sense?