2

I'm confused with javascript modules and classes. I'm trying to create an object of my class, but it always says "cannot set property of undefined" or "object has no method". There is my module 2.js:

(function() {

var Game = function() {
    this.state = 'a';
};

Game.prototype.somefunc = function() {
    console.log(this.state);
};

})();

This is the main app code:

var g = require('./2.js');

var mygame = new g.Game;
mygame.somefunc();

//undefined is not a function error

or

var g = require('./2.js');

var mygame = g.Game;
mygame.somefunc();

//cannot call method of undefined error

What am I doing wrong?

Shawn Chin
  • 84,080
  • 19
  • 162
  • 191
vspr
  • 39
  • 1
  • 5
  • You are not exporting your Game object (which is wrapped inside an anonymous closure function), try declaring (just a stop-gap workaround) the Game object like this `Game = function () {}` without the `var` keyword. – Arnab Sep 25 '12 at 10:18
  • [This answer](http://stackoverflow.com/a/5311377/615754) might help... – nnnnnn Sep 25 '12 at 10:29

1 Answers1

0

In your first Game function, it only exists inside the (function(){})() closure. Its in its own little universe and lives and dies inside.

You have to expose it to the outside.

The "var" in

var Game = function(){}

means that its only defined within the scope of the closure.

You need something like this:

var g = require('./2.js');

(function() {

    var Game = function() {
        this.state = 'a';
    };

    Game.prototype.somefunc = function() {
        console.log(this.state);
    };

    g.Game = Game;

})();

var mygame = new g.Game;
mygame.somefunc();

Now the exact way you code this is going to depend on exactly how 2.js is setup. This is simply to illustrate that the key line is

g.Game = Game;

We're opening a little wormhole so that Game can escape its microcosm universe of the self executing anonymous function closure.

Geuis
  • 41,122
  • 56
  • 157
  • 219
  • Thanks, it works. But my idea is to have shared code in a separate module. How can i create an object strictly from the required module? I mean all classes and functions are in module, but i just instantiate them in the main app. I think its a problem in my understanding of modules and exports – vspr Sep 25 '12 at 11:51
  • http://www.amazon.com/JavaScript-The-Good-Parts-ebook/dp/B0026OR2ZY/ref=sr_1_2?ie=UTF8&qid=1348574076&sr=8-2&keywords=javascript+the+good+parts – Geuis Sep 25 '12 at 11:55