Skip to content Skip to sidebar Skip to footer

Javascript: Referenceerror: Myclass Is Not Defined

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()

Solution 1:

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

Solution 2:

MyClass is defined into the local scope of the self-invoking function. You can try to initialize MyClass outside of the self-invoking function:

varMyClass;
(function() {

  MyClass = (function() {

    functionMyClass() {}

    MyClass.prototype.name = function(name) {};

    returnMyClass;

  })();

}).call(this);

Another thing you can do is:

(function() {
  this.MyClass = (function() {

    functionMyClass() {}

    MyClass.prototype.name = function(name) {};

    returnMyClass;

  })();

}).call(window);

In the code above you're simply invoking the anonymous function with the window context and setting value to the MyClass window's property (which makes MyClass global).

Another solution (which in my opinion is more unclear) is:

(function() {

  window.MyClass = (function() {

    functionMyClass() {}

    MyClass.prototype.name = function(name) {};

    returnMyClass;

  })();

}).call(this);

The only difference is that you explicitly say that the property MyClass of window will be equals to the result of the execution of the function.

Your CoffeeScript probably could be something like:

MyClass = undefined
(->
  MyClass = (->
    MyClass = ->
    MyClass::name = (name) ->

    MyClass
  )()
).call this

Post a Comment for "Javascript: Referenceerror: Myclass Is Not Defined"