1

I have simple class in coffeescript (this class is located in file.js.coffee):

class ExampleClass
  constructor: (arguments) ->   

  makeSTH: (page) -> 

  makeSTHElse: (data) =>

I have another coffee file. I included above file and I tried to create instance of ExampleClass this way:

/#= require file.js.coffee

class ExampleClass2
  constructor: (arguments) -> 
    @ex = new ExampleClass(sth)

But I got something like this:

ReferenceError: ExampleClass is not defined

I don't know how to correctly reference to ExampleClass. Thanks for all answers and sorry for my English.

1
  • /#= is not a directive have you tried //= file.js.coffee Commented May 14, 2014 at 16:13

1 Answer 1

2

CoffeeScript will compile each of the source file as a separated compilation unit. Each of the compilation unit will be wrapped inside a block, so that the global namespace won't be polluted by mistake. So, ExampleClass actually get compiled to something like:

(function () {
  var ExampleClass;
  ExampleClass = function (args) {}
  ...
}).call(this);

You can see that ExampleClass can only be accessed from the same source. In order to access it from other source file, you need to bind it to window.

class window.ExampleClass
  constructor: (args) ->
  ...

PS. you're not allowed to use arguments as formal parameter name in CoffeeScript, as it has special meaning in JavaScript.

And /#= require file.js.coffee is not valid in CoffeeScript, you need to remove the leading /. I think that's just a typo.

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

1 Comment

Yup. You can also do class @ExampleClass as well, which will bind it to window as well. It results in this.ExampleClass = function (args) {}..., where this is the window context.

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.