我正在学习Node.js,我正面临一个我很难理解的问题。
基本上,我从模块x中的类调用模块y中的类y的函数。在这个属于y的函数中,我指的是类x中的变量。但是,不幸的是,我收到一个错误,指出该变量未定义。
它还不清楚。所以这是一个代码:
模块x:
const y = new (require('./y'))
class x {
constructor() {
this.somevariable = 3
}
call() {
y.get()
}
}
module.exports = x
模块:
const x = new(require('./x'))
class y {
get() {
console.log(x.somevariable)
}
}
module.exports = y
指数:
const x = new(require('./x'))
x.call()
它返回x.somevariable未定义。为什么我会收到此错误?是否禁止召回调用另一个模块的模块?是因为它会创造一个“循环”吗?那么,我怎样才能解决我的问题?我是否必须将'this'作为函数y.get的参数?
谢谢!
我的代码:
指数
const handlingmessages = require('./handlingmessages')
handlingmessages.init()
const server = require('./server')
server.init()
服务器
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:
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()
鉴定
const handlingmessages = require('./handlingmessages')
class identification {
data(id) {
handlingmessages.clients.push(id)
// handlingmessages.clients id undefined!!!
}
}
module.exports = new identification()
我很抱歉 我只想将代码分成几个文件,以避免将所有代码放在一个BIG和LARGE文件中,使其更容易理解。
发布于 2019-03-05 09:24:56
所以,我找到了解决这个问题的方法:我必须要求初始化函数中的模块。
基本上:
handlingmessages:
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
https://stackoverflow.com/questions/-100006419
复制相似问题