【问题标题】:Access a function within an export module nodeJS访问导出模块 nodeJS 中的函数
【发布时间】:2018-10-12 09:51:48
【问题描述】:

即使我使用面向对象的语言(C++、C#、AS3)进行编程,JS 的基本用法仍然存在一些问题。

我需要的是在 nodeJS 中的 module.export 中访问一个函数。

我有这个 auth.js 文件,里面有一个函数:

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...
}

我想在我的 server.js 中调用updatePgXP()(类似这样):

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

一切正常,我只是不知道如何从外部访问 auth.js 中的函数。它需要留在导出模块中,因为它需要在 module.export 之后声明的 var 才能运行。

此时我调用函数updatePgXP() 时会触发未定义的错误。

非常感谢任何可以提供帮助的人。

【问题讨论】:

    标签: javascript node.js function class


    【解决方案1】:

    您必须导出对象而不是公开这些函数的函数。

    您还可以使用适当的构造函数创建一个类,该类允许您以面向对象的方式对这些变量进行操作:

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

    如果您使用的是 ES6,则可以使用适当的类构造:

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

    更多关于 JS 中的类:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-14
      • 1970-01-01
      • 1970-01-01
      • 2014-01-14
      • 1970-01-01
      • 2021-10-12
      • 2016-09-20
      相关资源
      最近更新 更多