首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >回调一个模块

回调一个模块
EN

Stack Overflow用户
提问于 2019-03-05 00:06:45
回答 1查看 0关注 0票数 0

我正在学习Node.js,我正面临一个我很难理解的问题。

基本上,我从模块x中的类调用模块y中的类y的函数。在这个属于y的函数中,我指的是类x中的变量。但是,不幸的是,我收到一个错误,指出该变量未定义。

它还不清楚。所以这是一个代码:

模块x:

代码语言:javascript
复制
 const y = new (require('./y'))

    class x {

      constructor() {

        this.somevariable = 3

      }

      call() { 

        y.get()

      }

    }

    module.exports = x

模块:

代码语言:javascript
复制
 const x = new(require('./x'))

    class y {

      get() { 

        console.log(x.somevariable)

      }

    }

    module.exports = y

指数:

代码语言:javascript
复制
const x = new(require('./x'))

x.call()

它返回x.somevariable未定义。为什么我会收到此错误?是否禁止召回调用另一个模块的模块?是因为它会创造一个“循环”吗?那么,我怎样才能解决我的问题?我是否必须将'this'作为函数y.get的参数?

谢谢!

我的代码:

指数

代码语言:javascript
复制
const handlingmessages = require('./handlingmessages')
handlingmessages.init()

const server = require('./server')
server.init()

服务器

代码语言:javascript
复制
const net = require('net')
const handlingmessages = require('./handlingmessages')

class server {

    init() {

        this.server = net.createServer()
        this.server.on('connection', (socket) => {

            socket.on('data', (data) => handlingmessages.data(data, socket))

        })

        this.server.listen(4582, '127.0.0.1')

    }

}

module.exports = new server()

handlingmessages:

代码语言:javascript
复制
const identification = require('./identification')

class handlingmessages {

    init() {

        this.clients = []

    }

    data(data, socket) {

            var json = JSON.parse(data)
            switch(json.type) {

                case 'identification':
                    identification.data(json.id)
                break
                // etc...

            }

    }

}

module.exports = new handlingmessages()

鉴定

代码语言:javascript
复制
const handlingmessages = require('./handlingmessages')

class identification {

    data(id) {

        handlingmessages.clients.push(id)
        // handlingmessages.clients id undefined!!!

    }

}

module.exports = new identification()

我很抱歉 我只想将代码分成几个文件,以避免将所有代码放在一个BIG和LARGE文件中,使其更容易理解。

EN

回答 1

Stack Overflow用户

发布于 2019-03-05 09:24:56

所以,我找到了解决这个问题的方法:我必须要求初始化函数中的模块。

基本上:

handlingmessages:

代码语言:javascript
复制
class handlingmessages {

    init() {

        this.clients = []
        this.identification = require('./identification')

    }

    data(data, socket) {

        var json = JSON.parse(data)
        switch(json.type) {

            case 'identification':
                this.identification.data(json.id)
            break
            // etc...

        }

    }

}

module.exports = new handlingmessages()

这里有一个循环要求的解释:https//nodejs.org/api/modules.html#modules_cycles

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100006419

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档