Javascript: ReferenceError: MyClass is not defined

coffeescript, javascript

Solution

My class is defined inside a closure. Rather what you want to do is "eject" it into the outer scope by setting it to the window object:

(function() {

    var myClass = ...

    window.myClass = myClass;

}).call( this );

Update: It seems you wanted it in CoffeeScript. Here you go:

(->

  myClass = (->
    myClass = ->
    myClass::name = (name) ->

    myClass
  )()

  window.myClass = myClass

).call this

JSBin Demo

Problem

This is very basic. I try to instantiate a Class defined in an external .js file embedded. The code of the .js is simply this. ``` (function() { var MyClass; MyClass = (function() { function MyClass() {} MyClass.prototype.name = function(name) {}; return MyClass; })(); }).call(this); ``` And the HTML is this ``` <!DOCTYPE html> <html> <head> <title>Sample Page</title> <script src="file.js" type="text/javascript"></script> </head> <body> </body> </html> ``` If I try on the console to instantiate the class but I see a `ReferenceError: MyClass is not defined`: ``` var myVar myVar = new MyClass > ReferenceError: MyClass is not defined ``` If I try to call `MyClass` directly from console I get the same error ``` > ReferenceError: MyClass is not defined ``` I'm sure I missing something terrible obvious here but yet I can figure it out what. Updated: To create the javascript coded I'm using CoffeScript, the code is simply this. ``` class MyClass acc: (name) -> ``` The proposed answers codes when converted back to CoffeScript using http://js2coffee.org render into a different code and it still doesn't work. Wonder If there's a hint on CoffeScript to eject MyClass from local scope to the outer scope.

Original source