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
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.
This i because Role
is a function
not Object
. You need to call function
to return self
. And you should set roleName
as property of self
var Role = (function() {
var self = {};
self.roleName = 'TestingRoleName';
return self;
})();
Or you can change Role
to this.This is the way I recommend
var Role = {
roleName:'TestingRoleName'
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.