[英]Can't access variable in custom Node.js module
I am trying to have a module contain the information for different roles for a game but whenever I try and receive the data from the variables I create, it comes as undefined and/or I get errors saying something similar to saying the variable inside the data doesn't exist (such as the role's name). 我试图让一个模块包含游戏中不同角色的信息,但是每当我尝试从我创建的变量中接收数据时,它都是未定义的,并且/或者我在说类似于数据内变量的操作时出现错误不存在(例如角色名称)。
I've seen a bunch of tutorials do similar but I can't seem to figure out what I've done wrong. 我看过很多教程都做过类似的事情,但是我似乎无法弄清楚自己做错了什么。
My index file. 我的索引文件。
var express = require('express');
var app = express();
var serv = require('http').Server(app);
var RoleList = require('./_modules/RoleList');
var Socket = function() {}
Socket.list = {};
serv.listen(process.env.PORT || 4567);
console.log("Server started.");
var io = require('socket.io')(serv, {});
io.sockets.on('connection', function(socket) {
socket.id = Math.random();
Socket.list[socket.id] = socket;
console.log('Player Connected');
console.log('Role Name: ' + RoleList.testRole.roleName);
socket.on('disconnect', function() {
delete Socket.list[socket.id];
console.log('Player Disconnected');
});
});
RoleList Module RoleList模块
var Role = function() {
var self = {};
var roleName = 'TestingRoleName';
return self;
}
modules.exports = {
roleTest: Role
}
But upon running the server I get the results. 但是运行服务器后,我得到了结果。
Server started.
Player Connected
T:undefined
instead of 代替
T:TestingRoleName
Is anyone able to help with this? 有人能帮忙解决这个问题吗? I'd appreciate that so much :DI am likely doing something completely wrong but I can't seem to find an answer anywhere.
我非常感谢:DI很可能在做完全错误的事情,但是我似乎在任何地方都找不到答案。
This i because Role
is a function
not Object
. 这是因为
Role
是一个function
而不是Object
。 You need to call function
to return self
. 您需要调用
function
返回self
。 And you should set roleName
as property of self
并且您应该将
roleName
设置为self
属性
var Role = (function() {
var self = {};
self.roleName = 'TestingRoleName';
return self;
})();
Or you can change Role
to this.This is the way I recommend 或者您可以将
Role
更改为此。这是我推荐的方式
var Role = {
roleName:'TestingRoleName'
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.