4

If I want to use an object and its methods in another file, how would I set up my module.exports?

Object:

var Object = function ()
{ 
...
}

Object.prototype.foo = function (param)
{
...
}

Module.export:

module.exports = {
    Object : Object
}

or

module.exports = {
    Object : Object,
    foo : Object.prototype.foo
}

?

1
  • 1
    don't override Object Commented Mar 2, 2018 at 5:47

3 Answers 3

7

A few ways of doing this but if you're trying to access prototype methods from your other file, then you'll need to instantiate your constructor, something like:

For ex:

// lib.js

var YourThing = function () {
}

YourThing.prototype.someMethod = function () {
  console.log('do something cool');
}

module.exports = YourThing;

// index.js

var YT = require('./lib.js');
var yourThing = new YT();
yourThing.someMethod(); 
Sign up to request clarification or add additional context in comments.

Comments

0
module.exports = Object;

This will export your Object as a Module.

1 Comment

Would I be able to access all of its methods? Also, how would I call this object in the other file? var obj = require('./file.js') and var instance = new obj.Object()?
0

If your object is not renewed in your app, the best way to use it as an executed function with late binding of its prototype methods

const _ = require('lodash')
var Object = function ()
{ 
    ..
    _.bindAll(this); // at last bind all methods. this way you won't miss a method
}

Object.prototype.foo = function (param)
{
     ...
}

module.exports = new Object();

then you can call the functions like,

const myObj = require('./object-file')
myObj.myMethod();

If you need reusable component,

module.exports = Object;

const _obj = require('./object-file'); // you can call this way anywhere in any function and for every require, it creates a new object.
var object = new _obj();
_obj.anyMethod(); 

Comments

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.