1

So I've been looking at this post: What is the purpose of Node.js module.exports and how do you use it? and have been trying to make sense of it within the scope of JavaScript objects.

So if I have this in game.js:

var myObj = function() { 

    this.function1 = function(){
        ...
    };
};

exports.myObj = myObj;

In the other file I'm assuming that I would do something like this:

var RequiredObj = require('game.js');

or

var RequiredObj = require('game.js').myObj;

Where I get lost is how to then use this object and its function, also how to create a new instance of this object.

Would it be something like this?

RequiredObj.myObj.function1();

and

RequiredObj.myObj = new RequiredObj.myObj();

Also is there any limit to how big the object I'm passing is? Because in my actual script my game object is huge.

Community
  • 1
  • 1
Connor Black
  • 6,921
  • 12
  • 39
  • 70

1 Answers1

2

Assuming the "other file" is in the same directory as game.js, something like this should work:

var game = require('./game.js');

var mo = new game.myObj();

mo.function1();

A few things to note:

  • Modules within your project should be specified with a path -- leading with ./, ../, or /. Otherwise, require will only search for the module as a core module or in node_modules folders (e.g., via npm install).

  • myObj appears to be a constructor and function1 would be an instance method. So, RequiredObj.myObj.function1() will error as no instance is created.

  • On the other hand, RequiredObj.myObj = new RequiredObj.myObj() should work... once. This line sets over the reference to the constructor with a reference to an instance, rendering the constructor (mostly) inaccessible. ("Mostly" because it can still be available as RequiredObj.myObj.constructor, but declaring a new variable for the instance is generally simpler.)

Also is there any limit to how big the object I'm passing is?

ECMAScript doesn't define any explicit limits on the size of an Object. Though, you'll of course be limited by the hardware used to execute the application.

Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199