0

Even if I program with object-oriented languages (C++, C#, AS3) I have still some problems with the basic usage of JS for its form.

What I need is to make accessible one function inside a module.export in nodeJS.

I have this auth.js file with a function inside:

module.exports = function(app,passport,pg,user,razza){

    var Pg = pg;
    var User = user;
    var Razze = razza;

    updatePgXP: function (){
            console.log("!!!!!!!!!!!!!Add XP!!!!!!!!!!!!!");
    }

//....and the story goes on...
}

And I would like to call updatePgXP() in my server.js (something) like this:

var authRoute = require('./app/routes/auth.js')(app,passport,models.pg,models.user,models.razze);

//doing stuff, and at some point...

io.sockets.on('connection', function(socket){
   socket.on('send message', function(data){
      authRoute.updatePgXP();
   }
}

All is working perfectly, I just can't figure out how can I access the function inside the auth.js from outside. It needs to stay inside the export module because it will need the vars declared on top after the module.export to operate.

At this moment fires an undefined error on the function updatePgXP() when I call it.

Many thanks to anyone can help.

1 Answer 1

1

You have to export object instead of function that would expose these functions.

You can also create a class with proper constructor that would allow you to operate on these variables in object-oriented style:

module.exports = function MyClass(app,passport,pg,user,razza){
    this.pg = pg;
    this.user = user;
    this.razza = razza;
}

MyClass.prototype.updatePgXP = function (){
   // Note "this" here:
   console.log(this.pg);
   console.log("!!!!!!!!!!!!!Add XP!!!!!!!!!!!!!");
}

// This is how you instantiate it somewhere else:
const myClassInstance = new MyClass(app,passport,pg,user,razza);
myClassInstance.updatePgXP();

If you're using ES6, you can use proper class construct, though:

module.exports = class MyClass {
  constructor(app,passport,pg,user,razza){
    this.pg = pg;
    this.user = user;
    this.razza = razza;
  }

  updatePgXP() {
    // Note what's inside "this" here:
    console.log(this.pg);
    console.log("!!!!!!!!!!!!!Add XP!!!!!!!!!!!!!");
  }
}

// Instantiation is the same:
const myClassInstance = new MyClass(app,passport,pg,user,razza);
myClassInstance.updatePgXP();

More on classes in JS:

Sign up to request clarification or add additional context in comments.

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.